#!/bin/sh

if [ -f /mnt/ramdisk/do.unmount ]
then
    echo "Codeload in progress: Rejecting login request.  Please retry after codeload operation is complete."
    exit 1
fi

MAX_LOGINS=20
MCCLI_LOCKFILE=/mem/mccli.lock
MCCLI_CNTFILE=/mem/mccli.ctr

LOCK_FILE()
{
    (
        flock -x 99
        # Check if login counter file exists (create it if does'nt exist)
        if [ ! -f ${MCCLI_CNTFILE} ]
        then
            echo -n 0 > ${MCCLI_CNTFILE}
            chmod 666 ${MCCLI_CNTFILE}
            chmod 666 ${MCCLI_LOCKFILE}
        fi

        # Increment the number of logins
        i=$(cat ${MCCLI_CNTFILE})
        i=$((i+1))

        # Check if exceeds the number of max logins
        if [ $i -gt ${MAX_LOGINS} ]
        then
            echo "Exceeded max logins of ${MAX_LOGINS}, terminating connection"
            exit 1
        fi

        # Update the login counter file
        echo -n $i > ${MCCLI_CNTFILE}
    ) 99>${MCCLI_LOCKFILE}
}

UNLOCK_FILE()
{
    trap '' SIGHUP EXIT SIGINT SIGTERM SIGQUIT SIGILL SIGABRT SIGFPE SIGKILL SIGSEGV SIGPIPE
    (
        flock -x 99

        # Decrement the number of logins (never go below 0)
        i=$(cat ${MCCLI_CNTFILE})
        i=$((i-1))
        if [ $i -lt 0 ]
        then
            i=0
        fi
        echo -n $i > ${MCCLI_CNTFILE}
    ) 99>${MCCLI_LOCKFILE}
}

LOCK_FILE

# Check if exceeded the number of logins
if [ $? -ne 0 ]
then
    # slow the failed connections
    sleep 30
    exit 1
fi

trap UNLOCK_FILE SIGHUP EXIT SIGINT SIGTERM SIGQUIT SIGILL SIGABRT SIGFPE SIGKILL SIGSEGV SIGPIPE
source /app/etc/app.env

SSH_PRE_LINE_FILE=/mem/.appuser_ssh
while getopts c opt $*
do
        case $opt in
        c)      shift
                if [ -f $SSH_PRE_LINE_FILE ]
                then
                    # Use the line count from the appshel file
                    nl=$(cat $SSH_PRE_LINE_FILE)
                else
                    # determine the number of lines from the commands to set api mode and disable pager
                    nl=`echo "set cli-parameters api pager off" | tr ';' '\n'  | mccli | wc -l`
                    echo $nl > $SSH_PRE_LINE_FILE
                fi
                # prepend the commands to set api mode and disable pager to the requested commands
                # remove the first nl (30) lines (output from the prepended commands)
                echo "set cli-parameters api pager off;$*" | tr ';' '\n'  | (mccli;ret=$?) | sed "1,$nl{d}"

                # bye
                exit $ret
                ;;
        esac
done
mccli
exit
