#!/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 "Remove virtualhost and associated user & database & db user from this server."
  echo ""
  echo "usage: $thisfilename -d <domain>"
  echo ""
  echo "  -h            Print this help."
  echo "  -d <domain>   Domain name of VirtualHost to remove."
  exit
}

vhost:getoptions "$@"

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

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

# check for database and delete if it exists
database=${domain//./dot}
database=${database//-/dash}
if [[ -d /var/lib/mysql/$database ]]; then
  /usr/local/bin/vhost-mysql-db-del.sh -d $domain
fi

# get & set username for this virtualhost
username=$(stat -c '%U' /srv/www/$domain)

# del virtualhost files & configs
/usr/local/bin/vhost-del.sh -d $domain

# check for any remaining virtualhosts before deleting user
# same check is done in vhost-user-del.sh
# but doing this here avoids generating any errors
existingvirtualhosts=false
vhost::set-virtualhostArray
for v in "${virtualhostArray[@]}"
do
  if [[ $(stat -c '%U' /srv/www/$v) = $username ]]; then
    existingvirtualhosts=true
  fi
done

if [[ $existingvirtualhosts == "false" ]]; then
  /usr/local/bin/vhost-user-del.sh -u $username
fi