#!/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 "Get System Users with info."
  echo ""
  echo "usage: $thisfilename [-u <username>] [-c] [-h]"
  echo ""
  echo "  -h            Print this help."
  echo "  -u <username> Only return info about specified username, otherwise all usernames are returned."
  echo "  -v            Verbose - include unencrypted passwords, if available."
  echo "  -c            CVS - Output in cvs format, instead of tabbed table."
}

vhost:getoptions "$@"
vhost::set-phpVersion

# create newline var
NL=$'\n'

# check for username (optional)
if [[ ! -z $username ]]; then
  if [[ -d "/home/$username" ]]; then
    usernames=$username
  else
    echo "ERROR: $username not found"
    exit 1
  fi
else
  usernames=(`ls /home/`)
fi

if [[ -n $verbose ]]; then
  output="uid username passwd jailed fpmmax"
else
  output="uid username jailed fpmmax"
fi

for username in "${usernames[@]}"
do
  userid=(`stat -c '%u' /home/$username`)
  if [[ -n $verbose ]]; then
    if [[ -f /home/$username/.passwd ]]; then
      password=(`awk -F : '{ print $2 }' /home/$username/.passwd`)
      if [[ -f /root/.vhost.ini ]]; then
        vhost::set-opensslpass
        password=`echo "$password" | openssl aes-256-cbc -d -a -pass pass:$opensslpass -pbkdf2`
      fi
    else
      password="(unknown)"
    fi
  fi
  shell=(`grep $username /etc/passwd|awk -F : '{ print $6 }'`)
  if [[ $shell = "/usr/jails/$username/./home/$username" ]]; then
    jailed="Yes"
  else
    jailed="No"
  fi

  fpmmax=0
  if [[ -f "/etc/php/$phpVersion/fpm/pool.d/$username.conf" ]]; then
    fpmmax=$(grep pm.max_children /etc/php/$phpVersion/fpm/pool.d/$username.conf | awk -F '=' '{ print $2 }' | tr -d ' ')
  fi

  if [[ -n $verbose ]]; then
    output="$output${NL}$userid $username $password $jailed $fpmmax"
  else
    output="$output${NL}$userid $username $jailed $fpmmax"
  fi
done

if [[ $cvs ]]; then
  echo "$output" | tr " " ","
else
  echo "$output" | column -t
fi