#!/usr/bin/bash
MGRCTL="/usr/local/mgr5/sbin/mgrctl"

function check_ismgr_ctl(){
    if [ ! -e "$MGRCTL" ];then
        echo "No mgrctl detected"
        exit 1
    fi
}

function get_ispmgr_web_config(){
    feature="$1"
    RESULT=$("$MGRCTL" -m ispmgr feature -o xml | /usr/bin/xmllint --xpath "//elem[name=\"web\"]/${feature}/text()" - 2>&1)
    RES_STATUS=$?
    if [ $RES_STATUS -eq 0 ]; then
        echo "$RESULT" | awk -F', ' '{print $1}'
        return 0
    else
        echo ""
        return $RES_STATUS
    fi
}

function get_users_list(){
    RESULT=$("$MGRCTL" -m ispmgr user -o xml | xmllint --xpath "//elem/name/text()" - 2>&1)
    RES_STATUS=$?
    if [ $RES_STATUS -eq 0 ]; then
        echo "$RESULT"
        return 0
    else
        echo ""
        return $RES_STATUS
    fi
}

function get_domains_list(){
    DOM_LIST=$("$MGRCTL" -m ispmgr webdomain -o xml)
    RES_STATUS=$?
    if [ $RES_STATUS -eq 0 ]; then
        RESULT=$(echo "$DOM_LIST" | xmllint --xpath "//elem/name[not(@orig)]/text()" - 2>/dev/null)
        RES_STATUS=$?
        if [ $RES_STATUS -ne 0 ]; then
            RESULT=""
        fi
        RESULT_ORIG=$("$MGRCTL" -m ispmgr webdomain -o xml | xmllint --xpath '//elem/name[@orig]/@orig' - 2>/dev/null | sed 's/\s*orig="\([^"]*\)"/\1/g' - )
        RES_STATUS=$?
        if [ $RES_STATUS -eq 0 ]; then
            if [ -n "$RESULT_ORIG" ]; then
                if [ -z "$RESULT" ]; then
                    echo -e "${RESULT_ORIG}"
                else
                    echo -e "${RESULT}\n${RESULT_ORIG}"
                fi
            else
                echo "${RESULT}"
            fi
        else
            echo "${RESULT}"
        fi
        return 0
    else
        echo ""
        return $RES_STATUS
    fi
}

check_ismgr_ctl
if [ -z "$1" ]; then
    echo "No command set"
    exit 1
fi
case "$1" in
    featlist)
        get_ispmgr_web_config "featlist"
        exit $?
    ;;
    status)
        get_ispmgr_web_config "status"
        exit 0
    ;;
    users)
        get_users_list
        exit 0
    ;;
    domains)
        get_domains_list
        exit 0
    ;;
    *)
        echo "Incorrect command"
    ;;
esac
exit 1

