#!/bin/bash
# v1.1.1

# verificare il posizionamento dei parametri nella stringa di START
# potrebbe variare in base al linguaggio utilizzato
params=''

executor=$(which python3)
startpath="/home/webmaster/webflussi"
startfile="webapp.py"
wholepath="$startpath/$startfile"

action=$1
#log_stdout=$2
#log_stderr=$3
log_stdout="$startpath/logs/flux_out.log"
log_stderr="$startpath/logs/flux_error.log"

# funzioni
print_usage() {
	printf "Usage: $0 (start|stop|status)\n"
}

get_pid() {
	#ps aux | grep -m1 $1 | grep -v grep |  awk '{print $2}'

	# approccio diverso: mi prendo TUTTI i possibili PID candidati e
	# successivamente scarto quelli che non mi servono
	# potrebbe (raramente) capitare che nel primo grep il processo
	# "ps aux | grep $1" esca come primo risultato (gli viene assegnato un
	# PID inferiore) e, di conseguenza, il flag -m1 va ad escludere l'altro
	# che contiene l'eseguibile vero e proprio che si stava cercando
	pid=$(ps aux | grep "$@")
	printf "$pid" | grep -v grep | awk '{print $2}'
}

get_netport() {
	# recupera la rete e la porta in ascolto del processo
	ss -tunapd | grep -e $(ps aux | grep -P '(?>'"$wholepath"').*' | grep -v grep | awk '{print $2}') | awk '{print $5}'
}

# main
if [ -z $1 ]; then
	print_usage >&2
	exit 1
fi

if [[ ! -d $(dirname $log_stdout) ]]; then
	mkdir $(dirname $log_stdout)
fi

if [[ $action == "start" ]]; then
	#	if [ $# -lt 3 ]; then
	#		>&2 print_usage
	#		exit 1
	#	fi
	nohup "$executor" $params "$wholepath" >>"$log_stdout" 2>>"$log_stderr" &
	sleep 1
	echo "Il progresso è in ascolto su "$(get_netport)
	exit 0
elif [[ $action == "stop" ]]; then
	pidexec=$(get_pid $wholepath)
	if [ -z $pidexec ]; then
		printf "Il processo non è attivo\n"
	else
		kill -15 $pidexec
	fi
	exit 0
elif [[ $action == "status" ]]; then
	pidexec=$(get_pid $wholepath)
	if [ -z $pidexec ]; then
		printf "Il processo non è attivo\n"
	else
		printf "Il processo è attivo con PID $pidexec\n"
		echo "Il progresso è in ascolto su "$(get_netport)
	fi
	exit 0
else
	print_usage >&2
	exit 1
fi
