#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Script      : check_reachability.py
# Chemin      : /usr/local/bin/check_reachability.py
# Description : Vérifie si une liste de serveurs web est atteignable en HTTPS ou HTTP et alerte par mail si non.
# Options     :
#   --hosts     Liste des domaines (sans http:// ni https://)
#   --log-file  Fichier de log (défaut /var/log/check_reachability.log)
#   --email     Destinataire mail en cas d’échec (défaut root@localhost)
# Exemples    :
#   ./check_reachability.py --hosts web1.com api.site.fr \
#       --log-file /var/log/check_reachability.log --email admin@exemple.com
# Prérequis   : Python 3, module requests (`pip install requests`)
# Auteur      : Sylvain SCATTOLINI
# Date Créé   : 2025-06-17
# Version     : 1.2
#

import argparse, logging, smtplib, datetime
from email.message import EmailMessage
import requests

TIMEOUT = 10

def send_email(to_addr, subject, body):
    msg = EmailMessage()
    msg.set_content(body)
    msg["Subject"] = subject
    msg["From"] = f"check@localhost"
    msg["To"] = to_addr
    with smtplib.SMTP("localhost") as s:
        s.send_message(msg)

def is_reachable(domain):
    for proto in ("https://", "http://"):
        url = proto + domain
        try:
            r = requests.head(url, timeout=TIMEOUT, allow_redirects=True)
            if r.status_code < 400:
                return True, proto, r.status_code
        except requests.RequestException:
            continue
    return False, None, None

def main():
    p = argparse.ArgumentParser(description="Test reachability HTTP/HTTPS")
    p.add_argument("--hosts",    nargs="+", required=True, help="Domaines à tester")
    p.add_argument("--log-file", default="/home/rms/logs/chk-web.log", help="Fichier de log")
    p.add_argument("--email",    default="si@medithau.com", help="Mail si échec")
    args = p.parse_args()

    logging.basicConfig(
        filename=args.log_file,
        level=logging.INFO,
        format="%(asctime)s [%(levelname)s] %(message)s",
        datefmt="%Y-%m-%dT%H:%M:%S"
    )

    down = []
    for h in args.hosts:
        ok, proto, code = is_reachable(h)
        if ok:
            logging.info(f"{h} → OK via {proto} (code={code})")
        else:
            logging.warning(f"{h} → DOWN")
            down.append(h)

    if down:
        body = ("Sites inatteignables :\n" +
                "\n".join(f"- {d}" for d in down) +
                f"\n\nTest effectué le {datetime.datetime.now():%Y-%m-%d %H:%M:%S}")
        send_email(
            args.email,
            "[ALERTE] serveurs inatteignables",
            body
        )
        exit(1)

if __name__ == "__main__":
    main()