#!/bin/bash
SERVICE="ssh"
PROCESS="sshd"
PORT=22
IPs="0.0.0.0 ::" #:: pour ipv6 

mode=$1
num=$2
function exit_error {
	echo $1
	exit 1
}

function test_tcp {
	port=$1

	shift
	for ip in $@
	do
		netstat -tan|tr -s " " " "|cut -d" " -f4,6|egrep "^$ip:$port LISTEN" && return 0;
	done
	netstat -tanp|egrep "$port" #tente d'afficher l'état du port en cas d'erreur
}


function test {
	service $SERVICE status || exit_error "The service $SERVICE isn't running"
	ps -C $PROCESS ||  exit_error "The process $PROCESS isn't find with ps" 	
	test_tcp $PORT $IPs || exit_error "The process doesn't listen in port $PORT on ips $IPs" 
	#add check_http
}

function rescue {
	case $1 in
		0) echo 1 ;; #Retourne le nombre de modes dispos
		1) service $SERVICE restart || exit_error "service $SERVICE restart FAIL" ;;
#		2) tenter une update	
		*) exit_error "Unknown rescue num:$1 for service $SERVICE";;
	esac
}

function save {
	echo "save"
}

function load {
	echo "load"
}

case $mode in
	test) test;;
	rescue) rescue $num;;
	save) save;;
	load) load;;
	*) echo "OP 1 must be : [test|rescue|save|load]"; exit 1
esac

exit 0
