#!/usr/bin/env bash

# Creates the file locally using arguments, then pushes the file to the remote
# SAS 9 server using SSH for execution.  Finally, deletes the file.
echo remove and recreate sasjsbuild folder
rm -rf sasjsbuild
mkdir sasjsbuild

echo "reading .env.sas9 file (from sasjs auth -t sas9)"
source .env.sas9

# extract password from sasjs encoding
echo $SAS_PASSWORD | cut -c 16- | base64 --decode | cut -c 201- >/tmp/tempfile.sh >.env.sas9.deleteFolder.sh
read PW < .env.sas9.deleteFolder.sh

# create the script to be executed on the server
echo creating script
cat > .env.sas9.deleteFolder.sh <<- EOM
#!/usr/bin/env bash
cd "/opt/sas/sas9/SASHome/SASPlatformObjectFramework/9.4/tools"
./sas-delete-objects \\
  "/30.SASApps/3030.Projects/303001.DataController/build2" \\
  -host sas.4gl.io -port 8561 \\
  -user '$SAS_USERNAME' -password "$PW" \\
  -deleteContents 2>&1
EOM

echo copy to server: allbow@sas.4gl.io
scp .env.sas9.deleteFolder.sh allbow@sas.4gl.io:~/deleteTheFolder.sh

echo update permissions
ssh allbow@sas.4gl.io <<'ENDSSH'
    chmod 777 deleteTheFolder.sh
ENDSSH

echo execute the script
ssh allbow@sas.4gl.io <<'ENDSSH'
    ./deleteTheFolder.sh > deleteTheFolder.log
ENDSSH

echo fetching the log
scp allbow@sas.4gl.io:~/deleteTheFolder.log ./sasjsbuild/deleteTheFolder.log

echo printing the log
cat ./sasjsbuild/deleteTheFolder.log

