#!/bin/bash
APP=bssapp
PRJ_ROOT=../
SVC_ROOT=${PRJ_ROOT}/svc
UI_ROOT=${PRJ_ROOT}/ui
DEST_IP=46.224.33.150

echo "Building ${APP} executable"
cd ${SVC_ROOT}
if [[ $OSTYPE == 'darwin'* ]]; then
  GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags="-w -s" -o ./$APP ./main.go
else
  GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags="-w -s" -o ./$APP ./main.go
fi


echo "Building SPA"
cd ${UI_ROOT}

quasar build

echo "Copying executables"
scp ${SVC_ROOT}/${APP} root@${DEST_IP}:/opt/${APP}/${APP}.new
scp ${SVC_ROOT}/.env root@${DEST_IP}:/opt/${APP}/.env
scp ${SVC_ROOT}/mail.env root@${DEST_IP}:/opt/${APP}/mail.env
# scp ${SVC_ROOT}/upgrader/upgrader root@${DEST_IP}:/opt/${APP}/upgrader

echo "Transferring additional files"
#rsync -azP ${PRJ_ROOT}/templates/ root@${DEST_IP}:/opt/${APP}/templates --delete
#rsync -azP ${PRJ_ROOT}/db/sqls root@${DEST_IP}:/opt/${APP} --delete
#rsync -azP ${SVC_ROOT}/fonts/ root@${DEST_IP}:/opt/${APP}/fonts --delete
#rsync -azP ${PRJ_ROOT}/db/migration/base root@${DEST_IP}:/opt/${APP}/migrate --delete
rsync -azP ${UI_ROOT}/dist/spa/ root@${DEST_IP}:/opt/${APP}/ui/dist/spa/ --delete

#echo "Migrating database"
#ssh root@${DEST_IP} "/opt/migrater -folder /opt/${APP}/migrate/base -db ${APP} -host 10.0.0.2 -tracker base -migrate-table symigrate -password tesnos.+ed"

echo "Updating system"
ssh root@${DEST_IP} "sudo systemctl stop ${APP}.service"
ssh root@${DEST_IP} "sudo rm /opt/${APP}/${APP}"
ssh root@${DEST_IP} "sudo mv /opt/${APP}/${APP}.new /opt/${APP}/${APP}"

ssh root@${DEST_IP} "chown -R ${APP}:${APP} /opt/${APP}"

ssh root@${DEST_IP} "sudo systemctl start ${APP}.service"

# remove compiled binary
cd ${SVC_ROOT}
rm -rf ./$APP
