#!/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 "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.exportspk.sh
read PW < .env.sas9.exportspk.sh

# create the script to be executed on the server
echo creating export script locally
cat > .env.sas9.exportspk.sh <<- EOM
  #!/usr/bin/env bash
  rm /tmp/dc.spk
  /tmp/dcspk.sh $SAS_USERNAME $PW
EOM

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

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

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

echo fetching the spk
scp allbow@sas.4gl.io:/tmp/dc.spk ./sasjsbuild/dc.spk

echo fetching the script
scp allbow@sas.4gl.io:/tmp/dcspk.sh ./sasjsbuild/dcspk.sh

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

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