#!/bin/sh
#----------------------------------------------------------------------------
# /var/install/bin/apache2-config-modules-phppgadmin-phppgadmin-web-user
#
# Creation:     2016-01-31 hb
# Last Update:  $Id$
#
# Copyright (c) 2016-@@YEAR@@ Holger Bruenjes, holgerbruenjes(at)gmx(dot)net
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#----------------------------------------------------------------------------

# include eislib
. /var/install/include/eislib

# include config
. /etc/config.d/apache2
. /etc/config.d/phppgadmin

#debug=true

if ${debug:-false}
then
    exec 2>/tmp/$(basename ${0})-trace$$.log
    set -x
    ask_debug=true
    export ask_debug
fi

ASK="/var/install/bin/ask"
CHOOSE='/var/install/bin/choose'
MKTEMP='/usr/bin/mktemp'
AWK='/usr/bin/gawk'
SED='/usr/bin/sed'
RM='/usr/bin/rm'
CAT='/usr/bin/cat'
SORT='/usr/bin/sort'
WC='/usr/bin/wc'
package_path='/srv/www/phppgadmin'

alias='phppgadmin'

project_name='PHPPGADMIN'

# set echo line, for allways equal
echo_line="  ----------------------------"

# ---------------------------------------------------------------------------
# select project
# ---------------------------------------------------------------------------
select_to_work()
{
    clrhome

    mecho -n --info 'Password settings for '
    mecho -n --std  "'${alias}' "
    mecho --info    'web access'
    echo

    AW_ROWS=0

    eval _ac_con='${'${project_name}'_ACCESS_CONTROL}'

    if [ "${_ac_con:-no}" = 'yes' ]
    then
        eval _ac_auth='${'${project_name}'_ACCESS_AUTH}'

        if [ "${_ac_auth:-no}" = "yes" ]
        then

            clrhome
                # entry:action:message:para
            action_entry="show user:user_list:yes
                          add user:user_action:Add user to:-b
                          remove user:user_action:Remove user from:-D
                          alter password:user_action:Alter password for user from:-a"


            mecho  "Please select your action"
            echo

            techo --begin '3 3r 2 32'
            techo --row "" --info No "" --info Action
            mecho "${echo_line}"

            idx=1
            echo "${action_entry}" |
            while read line #entry action message para
            do
                  entry="$(echo "${line}" | awk -F':' '{print $1}')"

                  techo --row "" "${idx}." "" "${entry}"

                  idx=$((${idx} + 1))
            done
            mecho "${echo_line}"
            techo --end

            echo
            _ask_tmpfile=$(${MKTEMP} -t .XXXXXXXXXXXXX)
            ${ASK} "Select" "" "1-$(echo "${action_entry}" | ${WC} -l)" "^$=Return" "0=Exit" >${_ask_tmpfile}
            rc=${?}
            read action_to_do < ${_ask_tmpfile}
            ${RM} -f ${_ask_tmpfile}

            if [ ${rc} = 255 ]
            then
                action_to_do=0
            fi

            case ${action_to_do} in
            '') exit 0             ;;
            0)  exit 0             ;;
            *)
                # get action line
                action_line="$(echo "${action_entry}"   |
                              ${SED} -n "${action_to_do}p" |
                              ${SED} 's/^ *//')"

                action="$(echo "${action_line}" | ${AWK} -F':' '{print $2}')"
                message="$(echo "${action_line}" | ${AWK} -F':' '{print $3}')"
                para="$(echo "${action_line}" | ${AWK} -F':' '{print $4}')"

                # user_action
                # user_list
                # ${2}         ${3}             ${4}
                ${action}      "${message}"     "${para}"
                ;;
            esac
        fi
    fi
}
# ---------------------------------------------------------------------------
# user add, remove  or alter password to htpasswd file
# ---------------------------------------------------------------------------
user_action()
{
    action_string="${1}"
    action_flag="${2}"

    # write existing user to tty, without answer_line
    user_list "no"

    echo
    mecho -n "${alias} web user"
    echo
    _ask_tmpfile=$(${MKTEMP} -t XXXXXXXXXXXXX)
    ${ASK} "Name of user (ENTER=Return, 0=Exit)" "" "*" >${_ask_tmpfile}
    rc=${?}
    read UserName < ${_ask_tmpfile}
    ${RM} -f ${_ask_tmpfile}

    if [ ${rc} = 255 ]
    then
        UserName=0
    fi

#    if ! echo "${action_string}" | grep -q "Remove"
#    then
#        _used_project=${_selected_project}
 #   fi

    case ${UserName} in
        '') select_to_work     ;;
        0)  exit 0             ;;
        *)
            # add, remove or alter password
            select_pw_action ${action_flag} \
                --file ${package_path}/${alias}.htpasswd   \
                --realm ${alias} \
                --user ${UserName}

            # set rights
        #    chown wwwrun ${trac_path}/${_selected_project}.htpasswd
        #    chmod 0600 ${trac_path}/${_selected_project}.htpasswd
        ;;
    esac
}
# ---------------------------------------------------------------------------
# user list
# ---------------------------------------------------------------------------
user_list()
{
    answer_line=${1}

    clrhome

    # write user list to tty
    mecho -n "Existing user in project "
    mecho --info "'${alias}'"
    echo

    # read project password file
    techo --begin '3 32'
    techo --row "" --info User
    mecho "${echo_line}"

    ${CAT} ${package_path}/${alias}.htpasswd | ${SORT} |
    while read line #user passwd
    do

        user="$(echo "${line}" | ${AWK} -F':' '{print $1}')"
        passwwd="$(echo "${line}" | ${AWK} -F':' '{print $2}')"

        techo --row "" "${user}"
    done

    mecho "${echo_line}"
    techo --end

    if [ ${answer_line} != no ]
    then
        echo
        _ask_tmpfile=$(${MKTEMP} -t .XXXXXXXXXXXXX)
        ${ASK} "" "" "^$=Return" "0=Exit" >${_ask_tmpfile}
        rc=${?}
        read user_line < ${_ask_tmpfile}
        ${RM} -f ${_ask_tmpfile}

        if [ ${rc} = 255 ]
        then
            user_line=0
        fi

        case ${user_line} in
        '') select_to_work     ;;
        0)  exit 0             ;;
        esac
    fi
}
# ---------------------------------------------------------------------------
# select passwort action
# ---------------------------------------------------------------------------
select_pw_action()
{
    _create_pw_file=''
    _batch=''
    _alter=''
    _remove=''
    _entry_line=''
    _realm=''
    _pw_file=''
    _user=''

    while [ ${#} -gt 0 ]
    do
        case "${1}" in
        -c)
            _create_pw_file=true
            shift
            ;;
        -b)
            _batch=true
            shift
            ;;
        -a)
            _alter=true
            shift
            ;;
        -D)
            _remove=true
            shift
            ;;
        -e|--entry)
            _entry_line="${2}"
            shift 2
            ;;
        -r|--realm)
            _realm="${2}"
            shift; shift
            ;;
        -f|--file)
            _pw_file="${2}"
            shift; shift
            ;;
        -u|--user)
            _user="${2}"
            shift; shift
            ;;
        esac
    done

    if ! ${_remove:-false}
    then
        _ask_tmpfile=$(${MKTEMP} -t .XXXXXXXXXXXXX)
        ${ASK} "Create password with pwgen" "yes" >${_ask_tmpfile}
        rc=${?}
        read _passwd_pwgen < ${_ask_tmpfile}
        ${RM} -f ${_ask_tmpfile}

        if [ ${rc} = 255 ]
        then
            exit 127
        fi

        if [ "${_passwd_pwgen}" = "yes" ]
        then
            # entry in passwdlib
            # create password
            # pwgen --help
            # return password
            get_pwgen_passwd
        else
            # entry in passwdlib
            # get password from cmdline
            get_passwd --check
        fi

        # entry in passwdlib
        # create the password-file entry line
        # return _passwd_entry
        get_digest_entry --user ${UserName} \
                         --realm ${alias} \
                         --passwd ${password}
    fi

    # entry in passwdlib
    set_passwd ${action_flag} \
               --user ${_user} \
               --file ${_pw_file} \
               --entry ${_passwd_entry:-dummy}

    if ! ${_remove:-false}
    then
        eval send_from='${'${project_name}'_ACCESS_AUTH_SEND_MAIL_FROM}'

        if [ -n "${send_from}" ]
        then
            _ask_tmpfile=$(${MKTEMP} -t .XXXXXXXXXXXXX)
            echo 'Send e-mail with [ENTER] to the given user'
            ${ASK} 'or type in the address:' "${_user}" "*" > ${_ask_tmpfile}
            rc=${?}
            read _send_mail < ${_ask_tmpfile}
            ${RM} -f ${_ask_tmpfile}

            if [ ${rc} = 255 ]
            then
                exit 127
            fi

            # entry in passwdlib
            send_passwd --user ${UserName} \
                        --realm ${alias} \
                        --passwd ${password} \
                        --mail ${_send_mail:-root} \
                        --sender ${send_from:-root}
        fi
    fi
}

# ---------------------------------------------------------------------------
# main
# ---------------------------------------------------------------------------
main()
{
    # include passwdlib
    . ${package_path}/passwdlib

    while true
    do
        clrhome

        active_project=''
        select_to_work

        echo
        _ask_tmpfile=$(/bin/mktemp -t .XXXXXXXXXXXXX)
        ${ASK} "One more action?" "no" > ${_ask_tmpfile}
        rc=${?}
        read more_action < ${_ask_tmpfile}
        ${RM} -f ${_ask_tmpfile}

        if [ ${rc} = 255 ]
        then
            more_action=no
        fi

        case ${more_action} in
        no)
            exit 0
            ;;
        esac
    done

    exit 0
}

# ---------------------------------------------------------------------------
# call function main
# ---------------------------------------------------------------------------
main "${@}"

# ---------------------------------------------------------------------------
# end
# ---------------------------------------------------------------------------