#!/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 "Removes virtualhost from server."
  echo ""
  echo "usage: $thisfilename -d <domain> [-h]"
  echo ""
  echo "  -d <domain>   Domain name of VirtualHost to remove."
  echo "  -h            Print this help."
  exit
}

vhost:getoptions "$@"

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

# check for virtualhost dir
if [[ ! -d /srv/www/$domain ]]; then
  echo "virtualhost dir does not exist"
  exit 1
fi

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

# disable the apache conf and reload apache
if [[ -h /etc/apache2/sites-enabled/$domain.conf ]]; then
  a2dissite --quiet $domain
  systemctl --quiet is-active apache2 && systemctl --quiet reload  apache2
fi

# remove the apache config
if [[ -f /etc/apache2/sites-available/$domain.conf ]]; then
  rm /etc/apache2/sites-available/$domain.conf
fi

# remove varnish config
if [[ -f /etc/varnish/sites.d/$domain.vcl ]]; then
  rm /etc/varnish/sites.d/$domain.vcl
  /usr/local/bin/vhost-varnish-update-sites.sh
  # don't bother to restart varnish as it will clear cache unnecessarily
fi

# if virtualhost is mounted in a jail, unmount it
if grep -q " /usr/jails/$username/srv/www/$domain " /etc/mtab; then
  umount /usr/jails/$username/srv/www/$domain
fi

# if virtualhost mount in fstab.jails exists remove it
if grep -q " /usr/jails/$username/srv/www/$domain " /etc/fstab.jails; then
  sed -i "\| /usr/jails/$username/srv/www/$domain |d" /etc/fstab.jails
fi

# if virtualhost symlink exists in jail remove it
if [[ -h /usr/jails/$username/home/$username/$domain ]]; then
  unlink /usr/jails/$username/home/$username/$domain
fi

# if virtualhost symlink exists in home dir remove it
if [[ -h /home/$username/$domain ]]; then
  unlink /home/$username/$domain
fi

# if virtualhost dir exists in jail remove it
if [[ -d /usr/jails/$username/srv/www/$domain ]]; then
  rm -r /usr/jails/$username/srv/www/$domain
fi

# remove virtualhost dir
if [[ -d /srv/www/$domain ]]; then
  rm -r /srv/www/$domain
fi