#!/bin/bash
#
# vmail-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 "$thisfilename"
  echo "Modify an existing user."
  echo ""
  echo "usage: $thisfilename -u <username> [-p <password>] [-x <fpmmax>] [-w <0|1>] [-h]"
  echo ""
  echo "  -h            Print this help."
  echo "  -u <username> System username to modify."
  echo "  -p <password> Updated password for username."
  echo "  -x <fpmmax>   Updated PHP-FPM pm.max_children value."
  echo "  -w <0|1>      Write user info to /home/username/.passwd (only applies when updating password)."
  echo "                0 = no, 1 = yes. Default is 1, which can be overridden in main config."
  exit
}

vhost:getoptions "$@"

# check for username
if [ -z "$username" ]; then
  echo "username not set"
  exit 1
fi

# verify user exists
if /bin/grep -q "^$username:" /etc/passwd; then

  # check for and change password
  if [[ -n "$password" ]]; then
    chpasswd <<<"$username:$password"
    if [[ $write == 1 ]]; then
      vhost::set-opensslpass
      encryptedpass=`echo -n "$password" | openssl aes-256-cbc -a -salt -pass pass:$opensslpass -pbkdf2`
      userid=(`stat -c '%u' /home/$username`)
      userpasswdinfo="$username:$encryptedpass:$userid:$userid::/home/$username:/bin/bash"
      if [[ -f "/home/$username/.passwd" ]]; then
        chmod 640 /home/$username/.passwd
      else
        install -o $username -g $username -m 640 /dev/null /home/$username/.passwd
      fi
      echo "$userpasswdinfo" > /home/$username/.passwd
    fi
  fi

  # check for and change php workers
  if [[ -n "$fpmmax" ]]; then
    vhost::set-phpVersion
    if [[ -f /etc/php/$phpVersion/fpm/pool.d/$username.conf ]]; then
      sed -i "s|pm.max_children.*|pm.max_children = $fpmmax|g" /etc/php/8.1/fpm/pool.d/$username.conf
    else
      echo "ERROR: PHP config for $username does not exist."
      exit 1
    fi
  fi

else
  echo "ERROR: User $username does not exist."
  exit 1
fi