#!/usr/bin/env bash
IFS=$'\n\t'
set -euo pipefail

#
# GovCMS restore database from backup.
#
# Accepts 1 argument for backup file (.sql or .sql.gz) path.
#

# Drush 12 support.
DRUSH="${GOVCMS_DRUSH:-none}"
if [ "$DRUSH" == "none" ]; then
  DRUSH=$(which /app/vendor/bin/drush > /dev/null 2>&1 && echo "/app/vendor/bin/drush" || echo "/usr/local/bin/drush")
fi

echo "GovCMS Deploy :: Restore Database"

STATUS=$("$DRUSH" status --fields=bootstrap --format=json)
if [ "$(jq -r '.bootstrap' 2> /dev/null <<< "$STATUS")" != "Successful" ]; then
  echo '[skip]: Site is not available.'
  exit 0
fi

if [ $# -eq 0 ]; then
  echo "[skip]: No backup file has been provided."
  exit 0;
elif [ $# -gt 1 ]; then
  echo "[skip]: Too many arguments, expecting one."
  exit 0;
fi

BACKUP_FILE=$1
echo "[info]: Importing backup file..."

if [[ $BACKUP_FILE == *".sql" ]]; then
  "$DRUSH" sql-drop -y
  "$DRUSH" sqlc < "$BACKUP_FILE" -vv
elif [[ $BACKUP_FILE == *".sql.gz" ]]; then
  "$DRUSH" sql-drop -y
  mkdir /tmp/restore
  gunzip -c "$BACKUP_FILE" > /tmp/restore/db-restore.sql
  "$DRUSH" sqlc < /tmp/restore/db-restore.sql -vv
  rm -rf /tmp/restore
elif [[ $BACKUP_FILE == *".tar.gz" ]]; then
  "$DRUSH" sql-drop -y
  mkdir /tmp/restore
  tar xfz "$BACKUP_FILE" --directory /tmp/restore
  # shellcheck disable=SC2012
  FILE=$(ls /tmp/restore/*.sql | head -1)
  "$DRUSH" sqlc < "$FILE" -vv
  rm -rf /tmp/restore
else
  echo "[skip]: Unsupported file type."
  exit 0;
fi

"$DRUSH" -y cache:rebuild
"$DRUSH" -y updatedb

echo "[success]: Completed successfully."
