#!/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

help()
{
  thisfilename=$(basename -- "$0")
  echo "Remove user from this server."
  echo ""
  echo "usage: $thisfilename username"
  echo ""
  echo "  -h            Print this help."
  exit
}

# check for and set username
if [ -n "$1" ]; then
  if [ $1 == "-h" ]; then
    help
  else
    username="${1,,}"
  fi
else
  echo "username not set"
  exit 1
fi

if ! /bin/grep -q "^$username:" /etc/passwd; then
  echo user \"$username\" does not exist
  exit 1
fi

vhost::set-virtualhostArray
for v in "${virtualhostArray[@]}"
do
  if [ $(stat -c '%U' /srv/www/$v) = $username ]; then
    echo "$username has one or more installed virtualhosts ($v)"
    exit 1
  fi
done

# check for jailed vhost mount
if /bin/grep -q "^/dev/sda /usr/jails/$username/srv/www/" /etc/mtab; then
  echo user \"$username\" has one or more jailed vhosts mounted
  exit 1
fi

# check for virtualhost jail mount(s) in fstab.jails
if /bin/grep -q " /usr/jails/$username/srv/www/" /etc/fstab.jails; then
  echo user \"$username\" has one or more jailed vhost mounts
  exit 1
fi

# checks complete, start removing stuff

# check for php-fpm pool conf
vhost::set-phpVersion
if [[ -f "/etc/php/$phpVersion/fpm/pool.d/$username.conf" ]]; then
  rm /etc/php/$phpVersion/fpm/pool.d/$username.conf
  # restart php$phpVersion-fpm if it's running
  if systemctl is-active --quiet php$phpVersion-fpm ; then
    if /usr/sbin/php-fpm$phpVersion -t >/dev/null 2>&1 ; then
      systemctl reload php$phpVersion-fpm
    else
      echo "WARNING: php-fpm$phpVersion configuration test failed"
    fi
  fi
fi

# if users home dir is mounted in a jail, unmount it
if grep -q "^/dev/sda /usr/jails/$username/home/$username " /etc/mtab; then
  umount /usr/jails/$username/home/$username
fi

# if user home dir mount in fstab.jails exists remove it
if grep -q "^/home/$username /usr/jails/$username/home/$username " /etc/fstab.jails; then
  sed -i "\|/home/$username /usr/jails/$username/home/$username|d" /etc/fstab.jails
fi

# delete user
/usr/sbin/userdel $username

# delete users home dir if it still exists
if [[ -d "/home/$username" ]]; then
  rm -r /home/$username
fi

# delete users jail dir if it exists
if [[ -d "/usr/jails/$username" ]]; then
  rm -r /usr/jails/$username
fi

# remove jailkit socket if it exists
if grep -q "\[/usr/jails/$username/dev/log\]" /etc/jailkit/jk_socketd.ini; then
  sed -i '/\/usr\/jails\/$username\/dev\/log/,+3 d' /etc/jailkit/jk_socketd.ini
  killall jk_socketd
  jk_socketd
fi