#!/bin/bash

set -eo pipefail

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
HOSTING_ENV="$1"
HOSTING_PATH="$2"
BACKUP_DIRECTORY="$3"

if [[ -z "$HOSTING_ENV" ]]; then
  echo "Argument 1: Hosting Env is missing."
  exit 1
fi
if [[ -z "$HOSTING_PATH" ]]; then
  echo "Argument 2: Hosting Path is missing."
  exit 1
fi
if [[ -z "$BACKUP_DIRECTORY" ]]; then
  BACKUP_DIRECTORY="~/backups"
fi

cd "$HOSTING_PATH"

# We are making the assumption that environments are on the same host for import.
# This isn't always the case and that's why this script is configurable.

if [[ ! -f ./vendor/bin/drush ]]; then
  echo "./vendor/bin/drush doesn't exist. Must be the first time a deployment has ever happened on this environment."
  echo "You will need to get the enviornment going the very first time manually."
  exit 1
fi
if [[ ! -d "$BACKUP_DIRECTORY" ]]; then
  echo "The backup directory $BACKUP_DIRECTORY doesn't exist."
fi
LATEST_BACKUP_FILENAME = "$( ls -t $BACKUP_DIRECTORY/*.sql.gz | head -n1 )"
if [[ -z $LATEST_BACKUP_FILENAME ]]; then
  echo "There are no backups in the backup directory $BACKUP_DIRECTORY."
fi
echo "Importing $BACKUP_DIRECTORY/$LATEST_BACKUP_FILENAME into the $HOSTING_ENV database."
gunzip < "$BACKUP_DIRECTORY/$LATEST_BACKUP_FILENAME" | ./vendor/bin/drush sqlc
