#!/bin/bash
set -euo pipefail
umask 077
LIST_FOLDER=${HARRESI_LIST_FOLDER:-/etc/harresi}
RULES_DIR=${HARRESI_IPTABLES_DIR:-/etc/iptables}
HOOKS_FILE=$LIST_FOLDER/firewall-hooks
TABLE=${1:-FORWARD}
TABLE=${TABLE^^}
case $TABLE in INPUT|OUTPUT|FORWARD|RESTORE|LIST|LIST-EDIT|SAVE) ;; *) echo 'ERROR: seleccione INPUT, OUTPUT o FORWARD.' >&2; exit 1 ;; esac
[[ $EUID == 0 ]] || { echo 'ERROR: esta operación requiere privilegios de administrador.' >&2; exit 1; }
if [[ $TABLE == LIST ]]; then
    case ${2:-} in blacklist|whitelist) ;; *) echo 'Lista no válida.' >&2; exit 1 ;; esac
    for file in "$LIST_FOLDER/$2"/*.list; do
        [[ -f $file ]] || continue
        printf '\n%s:\n' "$(basename "$file")"
        cat "$file"
    done
    exit
fi
if [[ $TABLE != RESTORE ]]; then
    lock=${HARRESI_SERVICE_LOCK:-/run/lock/harresi-services.lock}
    mkdir -p "$(dirname "$lock")"
    exec 9>"$lock"
    flock -x 9
fi
if [[ $TABLE == SAVE ]]; then
    [[ $# == 1 || ( $# == 2 && -f $2 && ! -L $2 ) ]] || { echo 'Uso: firewall-rules save [fichero regular]' >&2; exit 1; }
    work=$(mktemp -d)
    trap 'rm -rf "$work"' EXIT
    if [[ $# == 2 ]]; then cp -- "$2" "$work/candidate"; else iptables-save > "$work/candidate"; fi
    iptables-restore -w 5 --test < "$work/candidate"
    cp -p "$RULES_DIR/rules.v4" "$work/saved"
    iptables-save > "$work/live"
    recover_save() {
        trap - ERR HUP INT TERM
        cp -p "$work/saved" "$RULES_DIR/rules.v4"
        iptables-restore -w 5 < "$work/live" || echo 'CRÍTICO: recuperación del cortafuegos fallida.' >&2
        echo 'ERROR: configuración anterior restaurada.' >&2
        exit 1
    }
    trap recover_save ERR HUP INT TERM
    install -m 0600 "$work/candidate" "$RULES_DIR/rules.v4.new"
    mv "$RULES_DIR/rules.v4.new" "$RULES_DIR/rules.v4"
    if ! "${HARRESI_FIREWALL_HELPER:-/usr/local/sbin/harresi-apply-firewall}" auto active; then
        recover_save
    fi
    trap - ERR HUP INT TERM
    echo 'OK: configuración validada, guardada y aplicada con el modo seleccionado.'
    exit
fi
[[ -d $LIST_FOLDER/blacklist && -d $LIST_FOLDER/whitelist ]] || {
    [[ $TABLE != RESTORE ]] || exit 0
    echo "ERROR: faltan las listas en $LIST_FOLDER." >&2; exit 1
}
mkdir -p "$RULES_DIR"
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
iptables-save > "$work/previous"
compile_folder=$LIST_FOLDER
if [[ $TABLE == LIST-EDIT ]]; then
    kind=${2:-}; action=${3:-}; hook=${4:-}
    case $kind in blacklist|whitelist) ;; *) echo 'Lista no válida.' >&2; exit 1 ;; esac
    case $action in add|remove) ;; *) echo 'Acción no válida.' >&2; exit 1 ;; esac
    case $hook in INPUT|OUTPUT|FORWARD) ;; *) echo 'Hook no válido.' >&2; exit 1 ;; esac
    [[ $# -ge 5 ]] || { echo 'Falta una dirección IPv4.' >&2; exit 1; }
    shift 4
    compile_folder=$work/lists
    mkdir "$compile_folder"
    cp -a "$LIST_FOLDER/blacklist" "$LIST_FOLDER/whitelist" "$compile_folder/"
    [[ ! -f $HOOKS_FILE ]] || cp "$HOOKS_FILE" "$compile_folder/firewall-hooks"
    python3 - "$compile_folder/$kind" "$action" "$@" <<'PY'
import ipaddress,pathlib,sys
folder=pathlib.Path(sys.argv[1]); action=sys.argv[2]; requested=set()
for value in sys.argv[3:]:
    try:
        network=ipaddress.ip_network(value,strict=False)
        if network.version!=4: raise ValueError('solo IPv4')
        requested.add(str(network))
    except ValueError as e: raise SystemExit(f'ERROR: dirección {value} no válida: {e}')
existing=set()
for path in folder.glob('*.list'):
    rows=[]
    for row in path.read_text().splitlines():
        value=row.split('#',1)[0].strip()
        network=str(ipaddress.ip_network(value,strict=False)) if value else ''
        existing.add(network)
        if action!='remove' or network not in requested: rows.append(row)
    path.write_text('\n'.join(rows)+'\n')
if action=='add':
    with (folder/'menu.list').open('a') as out:
        for value in sorted(requested-existing): out.write(value+'\n')
PY
    TABLE=$hook
fi
python3 - "$compile_folder" "$TABLE" "$work/previous" "$work/candidate" "$work/hooks" <<'PY'
import ipaddress, pathlib, re, sys
folder, hook, source, target, hook_target = sys.argv[1:]
root = pathlib.Path(folder)
hooks_path = root/'firewall-hooks'
hooks = set(hooks_path.read_text().split()) if hooks_path.exists() else set()
# Migrate historical selected hooks without sharing a mutable chain.
text = pathlib.Path(source).read_text()
hooks.update(re.findall(r'^-A (INPUT|OUTPUT|FORWARD) -j HARRESI$', text, re.M))
if hook != 'RESTORE': hooks.add(hook)
if not hooks <= {'INPUT','OUTPUT','FORWARD'}: raise SystemExit('ERROR: firewall-hooks contiene un hook no válido.')
lists = {}
for kind in ('blacklist','whitelist'):
    addresses = []
    for path in sorted((root/kind).glob('*.list')):
        for number, raw in enumerate(path.read_text().splitlines(), 1):
            value = raw.split('#',1)[0].strip()
            if not value: continue
            try:
                network = ipaddress.ip_network(value, strict=False)
                if network.version != 4: raise ValueError('solo se admite IPv4')
            except ValueError as e:
                raise SystemExit(f'ERROR: {path}:{number}: dirección no válida ({value}): {e}')
            canonical = str(network)
            if canonical not in addresses: addresses.append(canonical)
    lists[kind] = addresses
lines = []
for line in text.splitlines():
    if re.search(r'(^:|^-A | -j )HARRESI(?:_(?:INPUT|OUTPUT|FORWARD))?(?: |$)',line): continue
    lines.append(line)
start = lines.index('*filter')
end = lines.index('COMMIT',start)
new = []
for h in sorted(hooks):
    chain = 'HARRESI_'+h
    new.append(f':{chain} - [0:0]')
# Insert hooks before pre-existing filter rules; only blacklist DROP terminates.
for h in sorted(hooks): new.append(f'-A {h} -j HARRESI_{h}')
for h in sorted(hooks):
    chain = 'HARRESI_'+h
    selectors = ['-s'] if h=='INPUT' else ['-d'] if h=='OUTPUT' else ['-s','-d']
    for kind in ('blacklist','whitelist'):
        action = 'DROP' if kind=='blacklist' else 'RETURN'
        label = 'BL' if kind=='blacklist' else 'WL'
        for address in lists[kind]:
            for selector in selectors:
                new.append(f'-A {chain} {selector} {address} -m limit --limit 12/min --limit-burst 20 -j LOG --log-prefix "HARRESI IPT {label} {h} " --log-level 4')
                new.append(f'-A {chain} {selector} {address} -j {action}')
    new.append(f'-A {chain} -j RETURN')
# Chain declarations must precede all append rules.
first_rule=next((i for i in range(start+1,end) if lines[i].startswith('-A ')),end)
declarations=[l for l in new if l.startswith(':')]
rules=[l for l in new if l.startswith('-A ')]
lines[first_rule:first_rule] = declarations+rules
pathlib.Path(target).write_text('\n'.join(lines)+'\n')
pathlib.Path(hook_target).write_text('\n'.join(sorted(hooks))+'\n')
for h in sorted(hooks): print(f'{h}: {len(lists["blacklist"])} entradas negras, {len(lists["whitelist"])} blancas; negra tiene prioridad.')
print('INPUT=origen; OUTPUT=destino; FORWARD=origen y destino del tráfico LAN/WAN. La lista blanca conserva la inspección y las demás restricciones.')
PY
if [[ $TABLE != RESTORE ]]; then
    mkdir "$work/original"
    cp -a "$LIST_FOLDER/blacklist" "$LIST_FOLDER/whitelist" "$work/original/"
    [[ ! -f $HOOKS_FILE ]] || cp -p "$HOOKS_FILE" "$work/original/firewall-hooks"
    [[ ! -f $RULES_DIR/rules.v4 ]] || cp -p "$RULES_DIR/rules.v4" "$work/original/rules.v4"
fi
iptables-restore -w 5 --test < "$work/candidate"
if ! iptables-restore -w 5 < "$work/candidate"; then
    iptables-restore -w 5 < "$work/previous" || echo 'CRÍTICO: no se pudo recuperar el cortafuegos.' >&2
    echo 'ERROR: reglas no aplicadas; selección anterior conservada.' >&2
    exit 1
fi
if [[ $TABLE != RESTORE ]]; then
    recover_commit() {
        trap - ERR HUP INT TERM
        rm -rf "$LIST_FOLDER/blacklist" "$LIST_FOLDER/whitelist"
        cp -a "$work/original/blacklist" "$work/original/whitelist" "$LIST_FOLDER/"
        for name in firewall-hooks rules.v4; do
            destination=$HOOKS_FILE
            [[ $name != rules.v4 ]] || destination=$RULES_DIR/rules.v4
            if [[ -f $work/original/$name ]]; then cp -p "$work/original/$name" "$destination"; else rm -f "$destination"; fi
        done
        iptables-restore -w 5 < "$work/previous" || echo 'CRÍTICO: recuperación del cortafuegos fallida.' >&2
        echo 'ERROR: no se pudieron guardar las listas; configuración anterior recuperada.' >&2
        exit 1
    }
    trap recover_commit ERR HUP INT TERM
    if [[ $compile_folder != "$LIST_FOLDER" ]]; then
        for file in "$compile_folder/$kind"/*.list; do
            install -m 0600 "$file" "$LIST_FOLDER/$kind/$(basename "$file").new"
            mv -f "$LIST_FOLDER/$kind/$(basename "$file").new" "$LIST_FOLDER/$kind/$(basename "$file")"
        done
    fi
    install -m 0600 "$work/hooks" "$HOOKS_FILE.new"
    mv -f "$HOOKS_FILE.new" "$HOOKS_FILE"
    # Keep an applied snapshot for reboot; the mode helper strips temporary
    # mode/watchdog rules and reconstructs every saved list hook.
    install -m 0600 "$work/candidate" "$RULES_DIR/rules.v4.new"
    mv -f "$RULES_DIR/rules.v4.new" "$RULES_DIR/rules.v4"
    trap - ERR HUP INT TERM
    echo 'OK: listas aplicadas y selección de hooks guardada para el arranque.'
else
    echo 'OK: hooks de listas guardados restaurados.'
fi
