#!/bin/bash
#
# vhost-stack
# https://git.stack-source.com/msb/vhost-stack
# MIT License Copyright (c) 2021 Matthew Saunders Brown

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

# check for and set virtualhost
if [ -n "$1" ]; then
  virtualhost=$1
else
  echo "virtualhost not set"
  exit 1
fi

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

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

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

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

# remove varnish config
if [ -f /etc/varnish/sites.d/$virtualhost.vcl ]; then
  rm /etc/varnish/sites.d/$virtualhost.vcl
  /usr/local/bin/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 "^/dev/sda /usr/jails/$username/srv/www/$virtualhost " /etc/mtab; then
  umount /usr/jails/$username/srv/www/$virtualhost
fi

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

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

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

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

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