#!/bin/bash


function error(){
    printf "ERROR: "
    printf "$@"
    printf "\n"
}


function check_email(){
    local email="$1" ; shift
    case "$email" in
	*@*.*)
	    return 0
	    ;;
	*)
	    error "Invalid email: %s" "$email"
	    return 1
	    ;;
    esac
}


function check_name(){
    local name="$1" ; shift
    case "$name" in
	*' '*)
	    return 0
	    ;;
	*)
	    error "Invalid name: %s" "$name"
	    return 1
	    ;;
    esac
}


function no_check(){
    return 0
}

function read_password(){
    authpasswd
}

function ask(){
    local secret="$1";shift
    local check_fn="$1";shift
    local prompt="$(printf "$@")"
    local good=0
    local answer
    case "$secret" in
	1|secret|password)
	    secret=(-r -s)
	    ;;
	*)
	    secret=(-r -e)
	    ;;
    esac
    while [ $good -eq 0 ] ; do
	    read ${secret[@]} -p "$prompt" answer
	    if eval "$check_fn" "\"$answer\"" ; then
	        good=1
	    fi
    done
    echo "$answer"
}


function quote(){
    local text="$1";shift
    echo -n \'${text//\'/\'\'}\'
}

function email_domain(){
    local email="$1";shift
    echo "$email"|sed -e 's/.*@//'
}

function valid_domain_p(){
    local domain="$1";shift
    sudo -u postfix \
        psql --pset pager -q -1 -t -c 'select domain from domain where domain='"$(quote "${domain}")"';' \
        | grep -q -s "${domain}"
}


function mail_user_create(){
    local email="$1";shift
    local name="$1";shift
    local hpass="$1";shift
    # Create Maildir:
    cd /home/postfix/Maildir
    sudo -u postfix maildirmake "$email"
    # Create user account:
    sudo -u postfix psql <<EOF
INSERT INTO mailbox (username,password,name,maildir) VALUES ($(quote "$email"),$(quote "$hpass"),$(quote "$name"),$(quote "$email/"));
EOF
}

function hash_password(){
    local clear="$1";shift
    error "hash_password not implemented yet. use interactive mode."
    exit 1
}

mail_prompt="Mail user email (ex. pjb@informatimago.com): "
name_prompt="Mail user name (ex. Pascal Bourguignon):     "
pass_prompt="Mail user password (ex. vAmQE=RYX):          "

function main(){
	if [ $# -eq 3 ] ; then
	    email="$1"
	    name="$2"
	    clear_password="$3"
	    check_email    "$email"    || exit 1
	    check_name     "$name"     || exit 1
	    check_password "$password" || exit 1
        hashed_password="$(hash_password "$clear_pasword")"
	else
	    email="$(ask clear check_email "$mail_prompt")"
	    name="$(ask clear check_name "$name_prompt")"
	    #clear_password="$(ask secret check_password "$pass_prompt")"
        hashed_password=$(read_password)
	fi
    local domain="$(email_domain "$email")"
    if valid_domain_p "$domain" ; then
        mail_user_create "$email" "$name" "$hashed_password"
    else
        error "Email domain is not valid: %s" "$domain"
    fi
}

main "$@"
ViewGit