#!/bin/bash
#
# vhost-stack
# https://git.stack-source.com/msb/vhost-stack
# Copyright (c) 2023 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 "Create archive of virtualhost on this server. Includes website files, server configs and MySQL databases."
  echo ""
  echo "usage: $thisfilename -d <domain> [OPTIONS]"
  echo ""
  echo "  -h            Print this help."
  echo "  -d <domain>   Domain name of VirtualHost to create archive for."
  exit
}

vhost:getoptions "$@"

# check for domain (virtualhost)
if [[ -z $domain ]]; then
  echo "domain is required"
  exit
fi

if [[ -d /srv/www/$domain ]]; then
  username=$(stat -c '%U' /srv/www/$domain)
else
  echo "virtualhost for $domain does not exist"
  exit 1
fi

# create export of vhost settings
/usr/local/bin/vhost-exp.sh -d $domain

# copy user home dir
cp --archive --parents /home/$username /srv/www/$domain/.exp/

# make sure archive dir exists
if [[ ! -d /opt/archives ]]; then
  mkdir /opt/archives
fi

# create tarball
tar --directory=/srv/www/ -czf /opt/archives/$domain.tar.gz $domain