#!/bin/bash
#
# vhost-stack
# https://git.stack-source.com/msb/vhost-stack
# Copyright (c) 2022 Matthew Saunders Brown <matthewsaundersbrown@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

# load include file
source $(dirname $0)/vhost.sh

help()
{
  thisfilename=$(basename -- "$0")
  echo "$thisfilename"
  echo "Export vhost settings, for backups and/or migrating to a new server."
  echo ""
  echo "usage: $thisfilename -d <domain> [-v] [-h]"
  echo ""
  echo "  -h              Print this help."
  echo "  -d <domain>     Domain to export settings for."
  echo "  -v              Verbose - output instructions for sycning website to new server, if verbose option was enabled."
  exit
}

vhost:getoptions "$@"

# check for domain
if [[ -z $domain ]]; then
  echo "ERROR: domain name is required"
  exit 1
fi

if [[ -d /srv/www/$domain ]]; then

  # check for and remove existing export data
  if [[ -d /srv/www/$domain/.exp/ ]]; then
    rm -r /srv/www/$domain/.exp/
  fi

  # system username
  username=$(stat -c '%U' /srv/www/$domain)

  # create export dir
  install --owner=$username --group=$username --mode=750 --directory /srv/www/$domain/.exp/

  # apache config
  if [[ -f /etc/apache2/sites-available/$domain.conf ]]; then
    cp --archive --parents /etc/apache2/sites-*/$domain.conf /srv/www/$domain/.exp/
  fi

  # letsencrypt certificate
  if [[ -f /etc/letsencrypt/renewal/$domain.conf ]]; then
    cp --archive --parents /etc/letsencrypt/archive/$domain/ /srv/www/$domain/.exp/
    cp --archive --parents /etc/letsencrypt/live/$domain/ /srv/www/$domain/.exp/
    cp --archive --parents /etc/letsencrypt/renewal/$domain.conf /srv/www/$domain/.exp/
  fi

  # letsencrypt pem file
  if [[ -f /etc/ssl/letsencrypt/$domain.pem ]]; then
    cp --archive --parents /etc/ssl/letsencrypt/$domain.pem /srv/www/$domain/.exp/
  fi

  # php config
  vhost::set-phpVersion
  if [[ -f /etc/php/$phpVersion/fpm/pool.d/$username.conf ]]; then
    cp --archive --parents /etc/php/$phpVersion/fpm/pool.d/$username.conf /srv/www/$domain/.exp/
  fi

  # mysql
  basedatabase=${domain//./dot}
  basedatabase=${basedatabase//-/dash}
  database_array=(`mysql -s -N -e "SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = '$basedatabase' OR SCHEMA_NAME LIKE '$basedatabase\_%'" | tr '\n' ' ' | xargs`)

  if [[ ${#database_array[@]} -gt 0 ]]; then
    mkdir /srv/www/$domain/.exp/mysql/
    for database in "${database_array[@]}"; do
      mysqldump --opt --quote-names --events --databases $database > /srv/www/$domain/.exp/mysql/$database.sql
    done
  fi

  # output instructions for sycning website to new server, if verbose option was enabled.
  if [[ -n $verbose ]]; then

    # check for .passwd
    if [[ -f /home/$username/.passwd ]]; then
      password=$(cat /home/$username/.passwd | cut -d : -f 2)
      if [[ -f /root/.vhost.ini ]]; then
        vhost::set-opensslpass
        password=`echo "$password" | openssl aes-256-cbc -d -a -pass pass:$opensslpass -pbkdf2`
      fi
      write=1
    else
      echo "NOTICE: system users password not autodetected!"
      password=`/usr/bin/pwgen 12 1`
      write=0
    fi

    # get/set mysql user/pass info
    if [[ -f /srv/www/$domain/.my.cnf ]]; then
      dbuser=$(grep ^user= /srv/www/$domain/.my.cnf |cut -d = -f 2)
      dbpass=$(grep ^password= /srv/www/$domain/.my.cnf |cut -d = -f 2)
    # elif wp-config.php
    else
      echo "NOTICE: db user & password not autodetected!"
      dbuser=$username@$domain
      dbpass=password
    fi

    echo
    echo "Vhost configs for $domain have been exported."
    echo "To migrate to a new server run these commands (as root) from the new server:"
    echo ""

    echo "/usr/local/bin/vhost-user-add.sh -u $username -p \"$password\" -w $write"
    if [[ -d /usr/jails/$username ]]; then
      echo "/usr/local/bin/vhost-user-jail.sh -u $username >/dev/null 2>/dev/null &"
    fi
    echo "/usr/local/bin/vhost-add.sh -d $domain -u $username"
    echo "/usr/local/bin/vhost-mysql-db-add.sh -d $domain -u $dbuser -p $dbpass"

    servername=`hostname -f`
    echo "rsync -v --archive --exclude='.passwd' --rsh=/usr/bin/ssh root@$servername:/home/$username/ /home/$username/"
    echo "rsync -v --archive --exclude='.my.cnf' --rsh=/usr/bin/ssh root@$servername:/srv/www/$domain/ /srv/www/$domain/"

    #db import
    if [[ -f /srv/www/$domain/.exp/mysql/$database.sql ]]; then
      echo "mysql $database < /srv/www/$domain/.exp/mysql/$database.sql"
    fi

    # /etc/ configs
    if [[ -d /srv/www/$domain/.exp/etc ]]; then
      echo "cp -a /srv/www/$domain/.exp/etc/* /etc/"
      echo "rm -r /srv/www/$domain/.exp/"
      echo "systemctl reload apache2.service"
      echo "systemctl reload php7.4-fpm"
    fi

    echo
    echo "NOTE: check for PHP version on new server and adjust /srv/www/$domain/.exp/etc/php/ config and reload command accordingly"

  fi

else

  echo "Virtualhost for $domain does not exist."
  exit

fi