#!/bin/bash

help() {
	echo -en "Uso: "$(basename $0)" [OPCIONES]\n\n"
	echo -en "  -h, --help: muestra mensaje de error y finaliza.\n"
	echo -en "  -t, --to <email>: email destinatario.\n"
	echo -en "  -f, --from: email remitente.\n"
	echo -en "  -P, --password: contraseña del remitente.\n"
	echo -en "  -s, --subject: Concepto del email.\n"
	echo -en "  -H, --host: dominio o IP del servidor SMTP (necesita STARTTLS).\n"
	echo -en "  -p, --port: puerto TCP/IP del servidor SMTP (por defecto: $port).\n"
}

sendEmail() {
# sendEmail
	echo -en "$message" | mailx -Ssendwait -s "$subject" -S smtp-use-starttls -S smtp-auth=login -S smtp=smtp://$host:$port -S from="$from" -S smtp-auth-user="$from" -S smtp-auth-password="$pass" $to > /dev/null 2>&1
	return $?
}

getVirtualHosts() {
# getVirtualHost $virtualHostPath
	if [ ! -d $1 ];then
		echo -en "ERROR:\tEl directorio \"$1\" no existe.\n"
		exit 1
	fi
	cont=1
	for virtualHost in $(find -L "$1" -type f);do
		grep ^[[:space:]]*auth_basic "$virtualHost" > /dev/null 2>&1
		if [ $? -eq 0 ];then
			# Si tiene la directiva "auth_basic" activada no lo comprobamos
			continue
		fi
		linea=$(grep ^[[:space:]]*server_name "$virtualHost")
		if [ $? -ne 0 ];then
			# Si no tiene la directiva "server_name" no lo comprobamos
			continue
		fi
		for hostname in $linea;do
			hostname=$(echo "$hostname" | sed 's/;//g')
			if [ $hostname != "server_name" ] && [ $hostname != "localhost" ];then
				hostnames[$cont]=$hostname
				cont=$((cont+1))
			fi
		done
	done
	# Eliminar repetidos
	hostnames=($(echo "${hostnames[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' '))
	unset linea cont hostname
}

checkHostname() {
# checkHostname $domain
	if [ $# -ne 1 ];then
		echo -en "ERROR:\tError interno en checkHostname.\n"
		exit 1
	fi
	domain=$1
	httpCode=$(curl -L -s -o /dev/null -w "%{http_code}" "$domain")
	case $httpCode in
		2[0-9][0-9])
			# Sitio Disponible
			return 0
			;;
		*)
			# Se ha producido algún error
			return 1
			;;
	esac
}

# Variables iniciales
hostnames=""
hostnamesFail=""
email=true
to=""
from=""
pass=""
subject="WARNING: Virtual Host NO DISPONIBLE"
host=""
port="587"

# Leer Opciones
TEMP=$(getopt -q -o ht:f:P:s:H:p: --longoptions help,to:,from:,password:,subject:,host:,port: --name $(basename $0) -- "$@")
eval set -- $TEMP
unset TEMP
while true; do
	case $1 in
		-h|--help)
			help
			exit 0
			;;
		-t|--to)
			to=$2
			shift 2
			;;
		-f|--from)
			from=$2
			shift 2
			;;
		-P|--password)
			pass=$2
			shift 2
			;;
		-s|--subject)
			subject=$2
			shift 2
			;;
		-H|--host)
			host=$2
			shift 2
			;;
		-p|--port)
			port=$2
			shift 2
			;;
		--)
			# Ultimo
			shift
			break
			;;
		*)
			# Inesperado
			help
			exit 1
			;;
	esac
done
if [ -z $to ] && [ $email = true ];then
	echo -en "WARNING(TO): El envio de correo está desactivado (Compruebe comfiguración).\n"
	email=false
fi
if [ -z $from ] && [ $mail = true ];then
	echo -en "WARNING(FROM): El envio de correo está desactivado (Compruebe comfiguración).\n"
	email=false
fi
if [ -z $pass ] && [ $email = true ];then
	echo -en "WARNING(PASSWORD): El envio de correo está desactivado (Compruebe comfiguración).\n"
	email=false
fi
if [ -z $host ] && [ $email = true ];then
	host=$(echo "$from" | cut -d '@' -f 2)
	host=$(dig -t MX "$host" +short | cut -d ' ' -f 2 | sed 's/.$//' | head -1)
	if [ -z $host ];then
		echo -en "WARNING(HOST): El envio de correo está desactivado (Compruebe comfiguración).\n"
		email=false
	fi
fi

# Comienza el programa
echo -en $(date +'[%Y-%m-%d] %H:%M:%S')" Comprobando Virtual Hosts...\n"
getVirtualHosts "/etc/nginx/sites-enabled/"
for hostname in ${hostnames[@]};do
	checkHostname $hostname
	if [ $? -ne 0 ];then
		echo -en "* \"$hostname\"\tNO ESTÁ DISPONIBLE.\n"
		hostnamesFail=$hostnameFail"* ""$hostname"" NO ESTÁ DISPONIBLE.\n"
	else
		echo -en "* \"$hostname\"\t ESTÁ DISPONIBLE.\n"
	fi
done

if [ ! -z $hostnamesFail ] && [ $email = true ];then
	echo -en "Enviando informe por email a \$TO..."
	sendEmail
	if [ $? -ne 0 ];then
		echo -en "WARNING:\tNo ha sido posible enviar email (REVISE CONFIGURACIÓN).\n"
	fi
fi