#!/bin/bash

#COMMON VARIABLES
DB_NAME="diunabi-morska"
BACKUP_FILE="${DB_NAME}-dev.bak"
#LOCAL VARIABLES
LOCAL_BACKUP_DIR="/Users/mz/Projects/Diuna/DiunaBI/Temp"
LOCAL_BACKUP_PATH=${LOCAL_BACKUP_DIR}/${BACKUP_FILE}
#DOCKER VARIABLES
DOCKER_BACKUP_DIR="/var/opt/mssql/backup"
DOCKER_CONTAINER_NAME="diuna-mssql-2022"
DOCKER_SA_PASSWORD="$&#ojoOOKEJ223"
DOCKER_SQLCMD="/opt/mssql-tools18/bin/sqlcmd"
DOCKER_BACKUP_PATH=${DOCKER_BACKUP_DIR}/${BACKUP_FILE}
#SERVER VARIABLES
REMOTE_HOST="bim-it.pl"
REMOTE_USER="mz"
REMOTE_SA_PASSWORD="9832&^*&huihj"
REMOTE_BACKUP_DIR="/tmp"

ssh ${REMOTE_USER}@${REMOTE_HOST} "sudo rm ${REMOTE_BACKUP_DIR}/${BACKUP_FILE}"
ssh ${REMOTE_USER}@${REMOTE_HOST} "/opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P '${REMOTE_SA_PASSWORD}' -Q \"BACKUP DATABASE [${DB_NAME}] TO DISK = '${REMOTE_BACKUP_DIR}/${BACKUP_FILE}'\""
scp ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_BACKUP_DIR}/${BACKUP_FILE} ${LOCAL_BACKUP_DIR}/

podman exec -i ${DOCKER_CONTAINER_NAME} mkdir -p ${DOCKER_BACKUP_DIR}
podman cp "${LOCAL_BACKUP_PATH}" "${DOCKER_CONTAINER_NAME}:${DOCKER_BACKUP_PATH}"
podman exec --user=root -i ${DOCKER_CONTAINER_NAME} chown mssql:mssql "$DOCKER_BACKUP_PATH"

LOGICAL_FILE_INFO=$(podman exec -i ${DOCKER_CONTAINER_NAME} ${DOCKER_SQLCMD} -C -S localhost -U SA -P "${DOCKER_SA_PASSWORD}" -Q "RESTORE FILELISTONLY FROM DISK = '${DOCKER_BACKUP_PATH}'" 2>&1)
DATA_FILE=$(echo "$LOGICAL_FILE_INFO" | awk 'NR==3 {print $1}' | tr -d '[:space:]')
LOG_FILE=$(echo "$LOGICAL_FILE_INFO" | awk 'NR==4 {print $1}' | tr -d '[:space:]')

RESTORE_OUTPUT=$(
  podman exec -i ${DOCKER_CONTAINER_NAME} ${DOCKER_SQLCMD} -C -S localhost -U SA -P "${DOCKER_SA_PASSWORD}" -Q "
  IF EXISTS (SELECT name FROM sys.databases WHERE name = '${DB_NAME}')
  BEGIN
      PRINT 'Database ${DB_NAME} exists. Dropping the database.';
      ALTER DATABASE [${DB_NAME}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
      DROP DATABASE [${DB_NAME}];
  END;

  RESTORE DATABASE [${DB_NAME}]
  FROM DISK = '${DOCKER_BACKUP_PATH}'
  WITH MOVE '${DATA_FILE}' TO '/var/opt/mssql/data/${DB_NAME}.mdf',
       MOVE '${LOG_FILE}' TO '/var/opt/mssql/data/${DB_NAME}_log.ldf';
  " 2>&1
  )

echo $RESTORE_OUTPUT