#!/bin/sh
#< Frontend to the htpasswd command

HTPASSWDFILE=/usr/local/etc/httpd/users

usage() {
  {
     echo "Usage: `basename $0` [ [ -a | -d | -r ] username ]"
     echo "  -a   Add user"
     echo "  -d   Delete user"
     echo "  -r   Reset password"
  }  >&2
}

if [ `id -u` -ne "0" ]; then
  echo "You must be root to run this script" && exit 1
fi

if [ ! -e "${HTPASSWDFILE}" ]; then
  {
     echo "Error: ${HTPASSWDFILE} does not exist!"
     echo "Add at least one user manually with the command"
     echo "htpasswd -c ${HTPASSWDFILE} username"
     echo "to create the file"
  }  >&2
  exit 2
fi

if [ "$#" -eq "0" ]; then
  MODE="LIST"
else
  if [ "$#" -ne "2" ]; then
     usage && exit 1
  fi
  case $1 in
     "-a")     MODE="ADD"
               shift
               USERNAME=$1
               ;;
     "-d")     MODE="DELETE"
               shift
               USERNAME=$1
               ;;
     "-r")     MODE="RESET"
               shift
               USERNAME=$1
               ;;
     *)        usage && exit 1
  esac
fi

check_user_exists() {
  grep "^${USERNAME}:" ${HTPASSWDFILE} >/dev/null 2>&1
  return $?
}

case ${MODE} in
  "LIST")      # do list
               cut -d: -f1 ${HTPASSWDFILE}
               ;;
  "ADD")       # do add
               check_user_exists
               if [ "$?" -eq "0" ]; then
                  echo "Error: User ${USERNAME} does already exists" >&2
                  exit 4
               fi
               htpasswd ${HTPASSWDFILE} ${USERNAME}
               # will now prompt for password
               ;;
  "DELETE")    # do delete
               check_user_exists
               if [ "$?" -ne "0" ]; then
                  echo "Error: User ${USERNAME} does not exist" >&2
                  exit 4
               fi
               htpasswd -D ${HTPASSWDFILE} ${USERNAME}
               ;;
  "RESET")     # do reset
               # find password with htpasswd -n
               #Pa55word is DeRwGGdNE/AHU
               check_user_exists
               if [ "$?" -ne "0" ]; then
                  echo "Error: User ${USERNAME} does not exist" >&2
                  exit 3
               fi
               RESET_TO="DeRwGGdNE/AHU"
               sed "s|^\(${USERNAME}:\).*$|\1${RESET_TO}|" ${HTPASSWDFILE} > ${HTPASSWDFILE}.new
               mv ${HTPASSWDFILE}.new ${HTPASSWDFILE}
               chown apache:apache ${HTPASSWDFILE}
               ;;

esac

exit 0