
DESC="
# halts all service and create a backup
# if _prod exists on server then
#    - stop service
#    - save the state (but doesnt remove from folder)
#    - delete the folder
#    - delete docker images
#
# can be undo with unarchive.sh
--------------
"

PROD_FOLDER=_prod
SSH_PEM=~/aws/hope.pem
LAST_STATE_FOLDER=last_state/
CURRDATE=$(date +"%Y-%m-%d")


echo "$DESC"

# check if _prod exists
PROD_EXISTS=""
ssh ubuntu@palladineve.com -i $SSH_PEM "test -d $PROD_FOLDER"
PROD_EXISTS=`echo $?` # 1 if missing, 0 if exists
echo "PROD_EXISTS: $PROD_EXISTS (1 if missing, 0 if exists)"

if [ $PROD_EXISTS -eq 1 ]; then
    echo "No _prod folder on server"
    exit 1
fi

# stop service on server
ssh ubuntu@palladineve.com -i $SSH_PEM "cd $PROD_FOLDER && sudo docker compose down"

# export data
ssh ubuntu@palladineve.com -i $SSH_PEM "mkdir $LAST_STATE_FOLDER"
ssh ubuntu@palladineve.com -i $SSH_PEM "cp -r $PROD_FOLDER/be/pb_data $LAST_STATE_FOLDER"
ssh ubuntu@palladineve.com -i $SSH_PEM "cp -r $PROD_FOLDER/be/downloaded_etf $LAST_STATE_FOLDER"

# compress and version older service
ssh ubuntu@palladineve.com -i $SSH_PEM "sudo tar -czvf PROD_BCK_${CURRDATE}.tar.gz $PROD_FOLDER"
# remove older service
ssh ubuntu@palladineve.com -i $SSH_PEM "sudo rm -rf $PROD_FOLDER"

# delete images on server
ssh ubuntu@palladineve.com -i $SSH_PEM "sudo docker system prune -a --volumes -f"