#!/usr/bin/python3
"""Pare-feu firewalld depuis les Paramètres (root par pkexec, mot de passe de l'administrateur). Arguments
vérifiés : jamais de commande firewall-cmd arbitraire. Les changements qui peuvent couper l'accès au PC sont
annulés au bout de 60 secondes s'ils ne sont pas confirmés (« confirm »).
  auxinux-firewall enable | disable          active (installe firewalld au besoin) ou désactive le pare-feu
  auxinux-firewall profile public|home|trusted
  auxinux-firewall rule-add JSON | rule-update JSON | rule-delete ID | rule-toggle ID on|off
  auxinux-firewall zone-remove ZONE service|port|rich VALEUR   entrée d'un profil ajoutée hors d'AuxiNux
  auxinux-firewall log-denied off|unicast|all                  journal des connexions bloquées
  auxinux-firewall confirm | rollback        garder les changements ou revenir en arrière tout de suite"""
import json
import os
import sys

sys.path.insert(0, os.environ.get("AUXINUX_SHELL_PYTHON", "/usr/share/auxinux-shell/python"))
from auxinux_shell.services import firewall_admin as admin  # noqa: E402
from auxinux_shell.services import firewalld as fw  # noqa: E402


def change_rule(old, new):
    """Applique le passage de old à new (l'un des deux peut être None) avec retour arrière si c'est risqué."""
    live = admin.running()
    if new is not None:
        admin.check_rule_keeps_ssh(new)
    if fw.is_risky(old, new):
        admin.begin_guard("rule")
    if old is not None:
        admin.apply_rule(old, False, live)
    try:
        if new is not None:
            admin.apply_rule(new, True, live)
    except admin.FirewallError:
        if old is not None:     # la nouvelle version est refusée : l'ancienne revient
            admin.apply_rule(old, True, live)
        raise


def rules_command(command, rest):
    rules = fw.load_rules()
    by_id = {rule["id"]: rule for rule in rules}
    if command in ("rule-add", "rule-update") and len(rest) == 1:
        try:
            data = json.loads(rest[0])
        except ValueError:
            raise ValueError("Règle invalide.")
        if command == "rule-add":
            data.pop("id", None)
        elif data.get("id") not in by_id:
            raise ValueError("Cette règle n'existe plus.")
        rule = fw.normalize_rule(data, admin.available_services() or None)
        old = by_id.get(rule["id"])
        change_rule(old, rule)
        rules = [rule if r["id"] == rule["id"] else r for r in rules] if old else rules + [rule]
        fw.save_rules(rules)
        print("Règle enregistrée.")
        return 0
    if command == "rule-delete" and len(rest) == 1:
        old = by_id.get(rest[0])
        if old is None:
            raise ValueError("Cette règle n'existe plus.")
        change_rule(old, None)
        fw.save_rules([r for r in rules if r["id"] != old["id"]])
        print("Règle supprimée.")
        return 0
    if command == "rule-toggle" and len(rest) == 2 and rest[1] in ("on", "off"):
        old = by_id.get(rest[0])
        if old is None:
            raise ValueError("Cette règle n'existe plus.")
        new = {**old, "enabled": rest[1] == "on"}
        if new == old:
            return 0
        change_rule(old if old["enabled"] else None, new if new["enabled"] else None)
        fw.save_rules([new if r["id"] == old["id"] else r for r in rules])
        print("Règle activée." if new["enabled"] else "Règle désactivée.")
        return 0
    return None


def zone_remove(zone, kind, value):
    if zone not in fw.PROFILES:
        raise ValueError("Profil inconnu.")
    live = admin.running()
    if kind == "service":
        if not fw.SERVICE_NAME.match(value):
            raise ValueError("Service inconnu du pare-feu.")
        ssh_ports = {22} if value == "ssh" else set()
    elif kind == "port":
        number, _sep, proto = value.partition("/")
        if proto not in ("tcp", "udp", "sctp", "dccp") or not fw.PORT_ITEM.match(number):
            raise ValueError("Port invalide.")
        low, _s, high = number.partition("-")
        ssh_ports = set(range(int(low), int(high or low) + 1)) if proto == "tcp" else set()
    elif kind == "rich":
        current = admin.query(f"--zone={zone}", "--list-rich-rules", live=live).splitlines()
        if value not in current:
            raise ValueError("Cette règle n'existe plus.")
        ssh_ports = set()
    else:
        raise ValueError("Type inconnu.")
    if any(port in ssh_ports for _peer, port in admin.ssh_state()["peers"]) and \
            admin.query("--get-default-zone", live=live).strip() == zone:
        raise ValueError("Ce retrait couperait la connexion SSH en cours.")
    admin.begin_guard("zone")
    flag = {"service": "--remove-service", "port": "--remove-port", "rich": "--remove-rich-rule"}[kind]
    admin.cmd(f"--zone={zone}", f"{flag}={value}", live=live)
    print("Retiré du profil.")
    return 0


def main(argv):
    command, rest = (argv[1], argv[2:]) if len(argv) > 1 else ("", [])
    try:
        if command in ("enable", "install") and not rest:
            return admin.enable()
        if command == "disable" and not rest:
            return admin.disable()
        if command == "confirm" and not rest:
            admin.confirm_guard()
            print("Changements gardés.")
            return 0
        if command == "rollback" and rest in ([], ["--timer"]):
            done = admin.rollback(from_timer=rest == ["--timer"])
            print("Configuration précédente rétablie." if done else "Rien à annuler.")
            return 0
        if not admin.installed() and command != "":
            print("Le pare-feu firewalld n'est pas installé.")
            return 1
        if command == "profile" and len(rest) == 1:
            admin.set_profile(rest[0])
            return 0
        if command == "log-denied" and len(rest) == 1 and rest[0] in fw.LOG_DENIED:
            code, output = admin.run(["firewall-cmd" if admin.running() else "firewall-offline-cmd",
                                      f"--set-log-denied={rest[0]}"])
            if code != 0:
                print(admin._reason(output, "firewall-cmd"))
                return 1
            print("Journal des connexions bloquées : " + rest[0])
            return 0
        if command == "zone-remove" and len(rest) == 3:
            return zone_remove(*rest)
        result = rules_command(command, rest)
        if result is not None:
            return result
    except ValueError as e:
        print(e)
        return 2
    except admin.FirewallError as e:
        print(e)
        return 1
    print(__doc__)
    return 64


if __name__ == "__main__":
    sys.exit(main(sys.argv))
