#!/bin/bash

PROG="${0##*/}"
MAILTO=postmaster

function usage() {
	echo "Usage: $PROG abonent=client|clientgroup param1=value1 param2=value2 ..."
	exit 1
}

function traff_usage() {
	cat <<THEEND
Usage: $PROG abonent=client|clientgroup [ip=<ipaddr> access_type=<access_type> name=<group_name>] 
	when abonent=client: ip and access_type must be present 
	when abonent=clientgroup: name must be present 
THEEND
    exit 1
}

function export_and_validate() {

	if [ $# = 0 ]; then
		echo "No args specified"
		usage
	fi
	export "$@"

	if [ $? != 0 ]; then
		echo "Wrong format."
		usage
	fi
	return 0
}

function validate_abonent() {
	if [ "$abonent" != "client" -a "$abonent" != "clientgroup" ]; then
		echo "Wrong abonent. Should be abonent=client|clientgroup"
		exit 2
	fi
	return 0;
}

function validate_ip() {

	if [ -z "$ip" ]; then
		echo "ip shouldn't be empty"
		usage
	fi

	IP=`echo $1 | grep -P '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'`
	if [ "$1" != "$IP" ]; then
		echo "Wrong IP"
		exit 3
	fi
	return 0
}

function init_and_validate() {
	export_and_validate "$@"
	validate_abonent
}

function mailto_client() {
	validate_ip
	echo "$access_type access for client with ip $ip is $1" | mail -s "Katrin: client access is $1" $MAILTO
}

function mailto_clientgroup() {
	if [ "$name" ]; then
		echo "$1 access for clientgroup $name is $2" | mail -s "Katrin: group access is $2" $MAILTO
	else
		echo "You didn't specified group name"
		usage
	fi
}

function is_group_action() {
# Does client action was called after clientgroup action?
	if [ "$group_action" ]; then
		return 1
	else
		return 0
	fi
}

