#!/usr/bin/env bash

function usage_and_exit () {
  cat <<END_OF_USAGE

USAGE:
  $0 --domain "example.tld" --website-tarball ~/example.tld.tar.gz --sql-dump ~/example.tld.sql

REQUIRED:
  --domain <domain>         The domain name of the site that is being transferred.
  --website-tarball <file>  The path to the tar+gzip archive file containing the contents of the docroot.
  --sql-dump <file>         The path to the SQL dump for the site.

OPTIONAL:
  --docroot <docroot>       The path to the document root of the domain. The default is ~/public_html/<domain>.
  --wp-cli <wp-cli>         The path to an existing wp-cli executable. The default is to use the WP-CLI installed by WP Toolkit.

END_OF_USAGE
  exit 1;
}

function error_and_exit () {
  echo -e "\nERROR: $*"
  usage_and_exit
}

function require_option () {
  if [ -z "$2" ]; then
    error_and_exit "The $1 option is required."
  fi
}

if [ "$EUID" -eq 0 ]; then
  echo "ERROR: This script should be run as the target user for the transfer, not as the root user."
  exit 1
fi

unset GETOPT_COMPATIBLE
# Exits with error status 4 when using a modern version of getopt.
getopt -T > /dev/null 2>&1
if [ $? != 4 ] ; then
  # The package is called util-linux on both RHEL-based and Ubuntu systems.
  echo "getopt from util-linux does not appear to be installed. Please ensure that util-linux is installed before continuing."
  exit 1;
fi

# Ensure any optional variables are not inherited from a parent process.
unset DOCROOT
unset WP_CLI

if [ -z "$*" ]; then usage_and_exit; fi
OPTS=$(getopt --name "$0" --options '' --longoptions domain:,docroot:,website-tarball:,sql-dump:,wp-cli:,help -- "$@")
if [ $? != 0 ]; then usage_and_exit; fi
eval set -- "$OPTS"

while [ "$*" ]; do
  case "$1" in
    --domain )
      if [ -z "$2" ]; then
        error_and_exit "The --domain value must not be empty."
      fi
      DOMAIN="$2"
      shift
      ;;
    --docroot )
      if [ ! -d "$2" ]; then
        error_and_exit "The value of --docroot must be an existing directory: $2"
      fi
      DOCROOT="$2"
      shift
      ;;
    --website-tarball )
      if [ ! -f "$2" ]; then
        error_and_exit "The value of --website-tarball must be a file that exists: $2"
      fi
      WEBSITE_ARCHIVE="$2"
      shift
      ;;
    --sql-dump )
      if [ ! -f "$2" ]; then
        error_and_exit "The value of --sql-dump must be a file that exists: $2"
      fi
      SQL_DUMP="$2"
      shift
      ;;
    --wp-cli )
      if [ -z "$2" ]; then
        error_and_exit "The --wp-cli value must not be empty."
      fi
      WP_CLI="$2"
      shift
      ;;
    --help )
      usage_and_exit
      ;;
    -- )
      shift
      break
      ;;
  esac
  shift
done

if [ "$*" ]; then
  error_and_exit "The following unknown argument(s) were present after any known options were processed: $*"
fi

require_option "--domain" "$DOMAIN"
require_option "--website-tarball" "$WEBSITE_ARCHIVE"
require_option "--sql-dump" "$SQL_DUMP"

# This can be overwritten with the --docroot option.
DOCROOT=${DOCROOT:="${HOME}/public_html/${DOMAIN}"}
if [ ! -d "$DOCROOT" ]; then
  error_and_exit "The docroot must be an existing directory: ${DOCROOT}"
fi

# This can be overwritten with the --wp-cli option.
WP_CLI=${WP_CLI:="/usr/local/bin/php /usr/local/cpanel/3rdparty/wp-toolkit/plib/vendor/wp-cli/vendor/wp-cli/wp-cli/php/boot-fs.php"}
if ! ${WP_CLI} --version | grep -q 'WP-CLI '; then
  error_and_exit "WP-CLI was not found or there was an error during execution: $WP_CLI --version\n\nPlease ensure that WP Toolkit is installed and available to this user, or use the --wp-cli option to provide a path to another WP-CLI installation."
fi

if ! openssl version > /dev/null; then
  error_and_exit "The 'openssl' command was not found or there was an error during execution. Please ensure that the 'openssl' command is available to this user."
fi

if ! uapi --help > /dev/null 2>&1; then
  error_and_exit "The 'uapi' command was not found or there was an error during execution. Please ensure that the 'uapi' command is available to this user."
fi

set -ex

tar xvzf "$WEBSITE_ARCHIVE" -C "$DOCROOT"
rm -fv "${DOCROOT}/.htaccess"

DATABASE_SUFFIX="wp_$(openssl rand -base64 16 | tr -d -c '[:lower:][:digit:]' | cut -b 1-5)"
DATABASE_USER_SUFFIX="wp_$(openssl rand -base64 16 | tr -d -c '[:lower:][:digit:]' | cut -b 1-5)"
DATABASE_PASSWORD="$(openssl rand -base64 20 | tr -d -c '[:alnum:]')"
DATABASE="${USER}_${DATABASE_SUFFIX}"
DATABASE_USER="${USER}_${DATABASE_USER_SUFFIX}"

uapi Mysql create_database name="$DATABASE"
uapi Mysql create_user name="$DATABASE_USER" password="$DATABASE_PASSWORD"
uapi Mysql set_privileges_on_database user="$DATABASE_USER" database="$DATABASE" privileges=ALL

mysql -u "$DATABASE_USER" -p"$DATABASE_PASSWORD" "$DATABASE" < "$SQL_DUMP"

$WP_CLI config set DB_NAME "$DATABASE" --path="$DOCROOT"
$WP_CLI config set DB_USER "$DATABASE_USER" --path="$DOCROOT"
$WP_CLI config set DB_PASSWORD "$DATABASE_PASSWORD" --path="$DOCROOT"
$WP_CLI config set DB_HOST localhost:3306 --path="$DOCROOT"

uapi WP add_domain domain="$DOMAIN" use_existing_wp_installation=1

set +x

if curl --version > /dev/null 2>&1; then
  echo -e "\nAfter site registration the web site title fetched from the local web server is:"
  curl -s -S -k -m 10 --resolve "${DOMAIN}:443:$(hostname -i)" "https://${DOMAIN}" | grep '<title>' ||:
fi

echo -e '\nDONE.'
