#!/bin/sh

# create a dir for authlog files
AUTHDIR="/tmp/auth"

BLOCKED_IP_LIST="/var/log/blocked_ip"
LOCKDIR="$AUTHDIR/lockdir"

# Sel logging variables, please refer netapp/include/sel.h for more info
# values under sel_component_t & sel_sev_t
SEL_PARAM="auth.notice"
SEL_LOGGER="/usr/local/bin/sel_logger"

num_params=$#
cmd_param=$1
ip_addr_param=$2

show_ipadds()
{
    if [ -e $BLOCKED_IP_LIST ]; then
        local num_lines=$(wc -l < $BLOCKED_IP_LIST);
    else
        local num_lines=0;
    fi
    
    if [ $num_lines -gt 0 ]; then
        echo "Blocked IP addresses: $num_lines"
        printf "%-21s%-35s%-20s\n" "IP address" "Time Blocked" "Blocked Mins"
        echo "--------------------------------------------------------------------"
        cat $BLOCKED_IP_LIST | awk -F'<::>' '{printf "%-20s%-35s%-20s\n", $1, $2, $3}'
    else
        echo "There are no blocked IP addresses"
    fi
}


#usage cases
usage ()
{
    echo "Usage:"
    echo "blocked_ip show"
    echo "blocked_ip clear ip_address"
    echo "blocked_ip clear all"
}

#main function
main ()
{
    # Wait for ssh_auth_parser.sh to finish if necessary
    count=0
    while [[  $count -le 3 ]]
    do
        if [ -e $LOCKDIR ]; then
            sleep 1;
            count=$(($count + 1));
        else
            break;
        fi
    done
    if [[ $count -le 3 ]]; then # If we obtained the lock
        case $1 in
            'show')
                show_ipadds
            ;;
            'clear')
                if [ -n "$2" ]; then
                    if [ $2 = 'all' ]; then
	                    /usr/local/bin/ssh_auth_parser.sh clear all
                    elif [ -n  "$2" ]; then
	                    /usr/local/bin/ssh_auth_parser.sh clear $2
                    fi
                else
                    echo "Second argument expected.";
                    usage;
                fi
            ;;
            *)
                echo "Unknown argument $1.";
                usage;
            ;;
        esac
    else
        echo "The system is currently busy, please try the command again."
    fi
}

#Start of the script.
if [ $# -gt 2 ] || [ $# -eq 0 ] ; then
    echo "Incorrect number of arguments."
    usage;
    exit 1;
fi
main $1 $2

exit 0
