#!/bin/sh
#
# gwck
#
# Copyright (C) 2008-2014 Simó Albert i Beltran
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#


#############
# Variables #
#############

# Program name.
PROGRAM_NAME="$(basename $0)"

# Configuration directory.
CONF_DIR="/etc/$PROGRAM_NAME"

# Main configuration file.
CONF_FILE="$CONF_DIR/${PROGRAM_NAME}_conf"

# Modules directory.
MODULES_DIR="$CONF_DIR/module"

# Run directory.
RUN_DIR="/var/run/$PROGRAM_NAME"

# Instance name.
INSTANCE="default"

# Seconds to wait after connection detect in loop mode
WAIT_CONNECT="10"

# Seconds to wait after disconnection detect in loop mode
WAIT_DISCONNECT="300"

# File to log
LOG_FILE="/var/log/$PROGRAM_NAME"

# IP adresses to test
HOSTS_TEST="4.2.2.4 141.1.1.1 8.8.8.8"

# Number of request packets to send to each target
PACKETS_NUMBER="20"

# Action modules.
MODULES=""

# Loop mode.
LOOP="false"


TERM="false"
connect="true"


#############
# Functions #
#############

##
# Show usage.
#
usage()
{
echo "
$PROGRAM_NAME

Usage:
 $0 arguments

Optional arguments:
 -h                     Show this help message.
 -i                     Instance name.
 -l	                    Set loop mode.
 -p \'host tests IP\'     Set hosts tests IP to ping.
 -m \'module1 module2'    Action modules, use \'none\' to disable configured modules.
 -f \'/path/to/file\'     Shellscript file to load at startup with configuration and/or functions.
 -k                     Kill all instances.

At startup the $(echo $CONF_FILE) file is imported as a shellscript, all arguments override the options in this file.

Arguments specified after -f argument override the possible configurations specified in the shellscript file specified in this argument.


Variables to configure:

INSTANCE			Instance name.
LOOP                Set loop mode (\'true\' or \'false\', default $(echo $LOOP)).
WAIT_CONNECT        Seconds to wait after connection detect in loop mode (default: $(echo $WAIT_CONNECT)).
WAIT_DISCONNECT     Seconds to wait after disconnection detect in loop mode (default: $(echo $WAIT_DISCONNECT)).
LOG_FILE            File to log (default: $(echo $LOGFILE)).
HOSTS_TEST          IP adresses to test (default: $(echo $HOSTS_TEST)).
PACKETS_NUMBER      Number of request packets to send to each target (default: $(echo $PACKETS_NUMBER)).
MODULES				Action modules.

"
}

##
# Print info message.
#
log()
{
	local log="$*"
	[ -z "$log" ] && log="$(cat)"
	if [ -n "$log" ]
	then
		echo "$(date) :: $INSTANCE : $log" | tee -a $LOG_FILE
	fi
}

##
# Print an error message.
#
error()
{
	log "
Error when $* !!
Aborted !!
"
	exit 1
}

##
# Test Internet connection.
#
gw_test()
{
	if echo "$HOSTS_TEST" | grep -q ":"
	then
		PING="ping6"
	else
		PING="ping"
	fi
	for i in $(seq 1 $PACKETS_NUMBER)
	do
		for host in $HOSTS_TEST
		do
			if $PING -c 1 -q $host > /dev/null 2>&1
			then
				return 0
			fi
		done
	done
	return 1
}

##
# Action when status connection changes.
#
action()
{
	local action="$1"
	for module in $MODULES
	do
		# Print start action message.
		if type ${PROGRAM_NAME}_mod_${module}_$action | grep -q 'shell function'
		then
			log "Start action $module $action."
			${PROGRAM_NAME}_mod_${module}_$action
			# Print end action message.
			log "End action $module $action."
		fi
	done
}

##
# Create run_enviroment.
#
create_run_enviroment()
{
	local instance=$INSTANCE
	local suffix="0"
	while [ -e $RUN_DIR/$INSTANCE ]
	do
		suffix="$(expr $suffix + 1)"
		INSTANCE="$instance-$suffix"
	done
	if [ "$instance" != "$INSTANCE" ]
	then
		log "Instance $instance renamed to $INSTANCE."
	fi
	mkdir -p $RUN_DIR/$INSTANCE
	echo $$ > $RUN_DIR/$INSTANCE/pid
}

##
# Delete run enviroment.
#
delete_run_enviroment()
{
	rm -rf $RUN_DIR/$INSTANCE
}

##
# Kill all instances.
kill_all_instances()
{
	for instance_run in $RUN_DIR/*
	do
		if [ -e $instance_run/pid ]
		then
			kill "$(cat $instance_run/pid)"
		fi
	done
	exit 0
}

##
# System signals function to terminate process.
#
term()
{
	# Check existing terminate process.
	if ! $TERM
	then
		# Don't exist a terminate process.
		TERM="true"
		# Terminate action.
		action term
		delete_run_enviroment
		$LOOP && log "Terminated."
		if $connect
		then
			exit 0
		else
			exit 1
		fi
	fi
}


##
# Config function.
#
config()
{

	if [ -e "$CONF_FILE" ]
	then
		. "$CONF_FILE" || error "importing $CONF_FILE shellscript file"
	fi

	# Initialization variables, parsing arguments.
	while getopts hi:le:p:m:f:k option ; do
		case $option in
			h)
				usage
				exit 0
			;;
			i)
				INSTANCE="$OPTARG" || error "setting instance name"
			;;
			l)
				LOOP="true" || error "setting loop mode"
			;;
			p)
				HOSTS_TEST="$OPTARG" || error "setting hosts test"
			;;
			m)
				MODULES="$OPTARG" || error "setting modules"
			;;
			f)
				. "$OPTARG" || error "importing sellscript file"
			;;
			k)
				kill_all_instances
			;;
			?)
				usage
				exit 1
			;;
		esac || error "setting arguments"
	done || error "parsing arguments"

	create_run_enviroment
	# Print start message if enabled loop mode.
	$LOOP && log "Start gwtest"

	for module in $MODULES
	do
		if [ -e $MODULES_DIR/$module ]
		then
			if . $MODULES_DIR/$module
			then
				log "$module module loaded."
			else
				error "reading $module module"
			fi
		fi
	done

	# Initial action.
	action init
}

#############
# Main code #
#############

config $@

# Traping system signals.
trap 'term' INT TERM KILL

# Looping.
while ! $TERM
do

	# Test Internet access.
	if gw_test
	then
		# Internet connection detected.
		# Print connection detected message if don't enabled loop mode or state changed.
		! $LOOP || ! $connect && log "Detect Internet connection."
		# Run connection action if enabled action mode and state chanded.
		# Check if previous state is disconnection.
		if ! $connect
		then
			# State changed.
			# Save connection state.
			connect="true"
			# Run connection action.
			action connect
		fi
	else
		# None Internet connection detected.
		# Print disconnection detected message if don't enabled loop mode or state changed.
		! $LOOP || $connect && log "None Internet direct connect."
		# Check if previous state is connection.
		if $connect
		then
			# State changed.
			# Save disconnection state.
			connect="false"
			# Run diconnection action.
			action disconnect
		fi
	fi

	# Wait if enabled loop mode.
	if $LOOP
	then
		if $connect
		then
			# Wait connection time.
			sleep $WAIT_CONNECT
		else
			# Wait disconnection time.
			sleep $WAIT_DISCONNECT
		fi
	fi

	# Break looping if don't enabled mode loop.
	! $LOOP && break

done

term
