#!/bin/bash
#
#
######################################
### Created by Vitaliy Razzhivin   ###
### Network Solution, 2015         ###  
### razzhivin@lanbilling.ru        ###
### LB-base-2.0-007+               ###
### LBucd                          ###
######################################

PARAMS="$*" # all parameters for ./handler from billing
LOG='/var/log/srvctl.log' # no comments

IPTABLES="/sbin/iptables" # path to iptables
SSH="/usr/bin/ssh" # path to ssh

NAS_IP="192.168.30.112" # router ip
SSH_USER="root" # user for ssh connecting

# flushing variables
ACTION=''
REASON=''
SESSION=''
LOGIN=''
NAS=''
IP=''
SHAPE=''
OLDSHAPE=''
BNGNAME=''
SUBSCRIBER=''
GUEST=''
PASSWORD=''
OLDBLOCKED=''
BLOCKED=''

log()
{
    echo "[`date +'%d-%m-%Y %H:%M:%S'`] (${LOGIN} ${IP}) - $1" >> $LOG # log regular events
}

log_error()
{
    echo "[`date +'%d-%m-%Y %H:%M:%S'`] - $1 [$PARAMS]" >> $LOG # log error events
}

# parsing handler parameters
while [ -n "$1" ]
do
    case $1 in
    "--action")
    ACTION=$2
    ;;
    "--reason")
    REASON=$2
    ;;
    "--session")
    SESSION=$2
    ;;
    "--login")
    LOGIN=$2
    ;;
    "--nas")
    NAS=$2
    ;;
    "--ip" | "--net")
    IP=$2
    ;;
    "--shape")
    SHAPE=$2
    ;;
    "--oldshape")
    OLDSHAPE=$2
    ;;
    "--opt-bng-name")
    BNGNAME=$2
    ;;
    "--mac")
    MAC=$2
    ;;
    "--guest")
    GUEST=$2
    ;;
    "--password")
    PASSWORD=$2
    ;;
    "--oldblocked")
        OLDBLOCKED=$2
        ;;
    "--blocked")
        BLOCKED=$2
        ;;
    *)
    log_error "Unknown parameters: $1, $2"
    ;;
    esac

    shift 2
done

# log_error "DEBUG"

if [ -z ${LOGIN} ]
then
    log_error "LOGIN is not defined"
    exit 1
fi

if [ -z ${IP} ]
then
    log_error "SHAPE is not defined"
    exit 1
fi

if [ -z ${NAS_IP} ]
then
    log_error "NAS is not defined"
    exit 1
fi

case $ACTION in
    "stop")
    echo "1" > /dev/null
    ;;
    "isg-stop")
        echo "1" > /dev/null
    ;;
    "quota")
        echo "1" > /dev/null
        ;;
    "start")
        echo "1" > /dev/null
        ;;
    "edit")
        echo "1" > /dev/null
        ;;
    "off")
        log "Switching off account"
    ${SSH} ${SSH_USER}@${NAS_IP} "${IPTABLES} -D FORWARD -s ${IP} -j ACCEPT; ${IPTABLES} -D FORWARD -d ${IP} -j ACCEPT"
        ;;
    "on")
        log "Switching on account"
    ${SSH} ${SSH_USER}@${NAS_IP} "${IPTABLES} -I FORWARD 1 -s ${IP} -j ACCEPT; ${IPTABLES} -I FORWARD 1 -d ${IP} -j ACCEPT"
        ;;
    "create")
        echo "1" > /dev/null
        ;;
    "delete")
        echo "1" > /dev/null
        ;;
    *)
        log_error "Unknown action $action"
        ;;
esac