#!/usr/bin/env python3
"""Stage, validate and release Harresi rules without touching active files early."""
import ast
import datetime
import fcntl
import glob
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import yaml

REPO = os.environ.get('HARRESI_RULES_REPO_BASE_URL', 'https://suricata-rules.harresi.es').rstrip('/')
STATE = Path(os.environ.get('HARRESI_RULES_STATE_DIR', '/var/lib/harresi/rules'))
CONF = Path(os.environ.get('HARRESI_SURICATA_CONF_DIR', '/etc/suricata'))
MANAGED = Path(os.environ.get('HARRESI_MANAGED_RULES_FILE', '/var/lib/suricata/rules/suricata.rules'))
LOCAL = Path(os.environ.get('HARRESI_LOCAL_RULES_FILE', '/var/lib/suricata/rules/harresi-local.rules'))
SOCKETS = Path(os.environ.get('HARRESI_SOCKET_DIR', '/run'))
RECOVERY = Path(os.environ.get('HARRESI_RULES_RECOVERY_FLAG', '/run/harresi-rules-recovery-required'))
UPDATE = CONF / 'update.yaml'
UNITS = ('suricata_ids', 'suricata_idps', 'suricata_mitm')


def run(args, **kwargs):
    return subprocess.run([str(a) for a in args], check=True, **kwargs)


def atomic(path, content):
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, temporary = tempfile.mkstemp(prefix='.' + path.name + '.', dir=path.parent)
    try:
        with os.fdopen(fd, 'wb') as out:
            out.write(content)
            out.flush()
            os.fsync(out.fileno())
        os.chmod(temporary, 0o640)
        os.replace(temporary, path)
    finally:
        Path(temporary).unlink(missing_ok=True)


def read_state():
    file = STATE / 'state.json'
    return json.loads(file.read_text()) if file.exists() else {'installed_version': 'none'}


def download(url, target):
    run(['curl', '--fail', '--silent', '--show-error', '--location', '--connect-timeout', '15', '--max-time', '120', url, '-o', target])


def release(requested, stage):
    if requested != 'latest' and not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]{0,80}', requested):
        raise ValueError('versión no válida')
    manifest_path = stage / 'manifest.json'
    download(REPO + ('/latest.json' if requested == 'latest' else f'/releases/{requested}/manifest.json'), manifest_path)
    manifest = json.loads(manifest_path.read_text())
    version, artifact, digest = (manifest.get(key, '') for key in ('version', 'artifact', 'sha512'))
    if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]{0,80}', version):
        raise ValueError('versión no válida en el manifiesto')
    if requested != 'latest' and requested != version:
        raise ValueError('el manifiesto no corresponde a la versión solicitada')
    if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]{0,180}', artifact):
        raise ValueError('nombre de paquete no válido')
    if not re.fullmatch(r'[0-9a-fA-F]{128}', digest):
        raise ValueError('SHA-512 no válido')
    archive = stage / artifact
    download(f'{REPO}/releases/{version}/{artifact}', archive)
    if hashlib.sha512(archive.read_bytes()).hexdigest().lower() != digest.lower():
        raise ValueError('el SHA-512 del paquete no coincide; no se instaló')
    raw = stage / 'harresi.rules'
    with tarfile.open(archive, 'r:gz') as tar:
        members = tar.getmembers()
        if any(m.issym() or m.islnk() or m.name.startswith('/') or '..' in Path(m.name).parts for m in members):
            raise ValueError('el paquete contiene rutas o enlaces no permitidos')
        # The publisher runs tar -C package ... ., producing ./rules/... .
        matches = [m for m in members if Path(m.name).as_posix() == 'rules/harresi.rules']
        if len(matches) != 1:
            raise ValueError('el paquete no contiene una única rules/harresi.rules')
        member = matches[0]
        if not member.isfile() or not 0 < member.size <= 64 * 1024 * 1024:
            raise ValueError('rules/harresi.rules vacío o demasiado grande')
        raw.write_bytes(tar.extractfile(member).read())
    # Apply the installed enable/disable/drop/modify filters in an isolated
    # data directory. Only the already verified local source is fetched here.
    update = {}
    if UPDATE.exists():
        installed = yaml.safe_load(UPDATE.read_text()) or {}
        for key in ('disable-conf', 'enable-conf', 'drop-conf', 'modify-conf', 'ignore'):
            if key in installed:
                update[key] = installed[key]
    update['sources'] = [raw.as_uri()]
    staged_update = stage / 'update-stage.yaml'
    staged_update.write_text(yaml.safe_dump(update))
    generated = stage / 'generated'
    run(['suricata-update', '-c', staged_update, '--data-dir', stage / 'data', '--output', generated,
         '--suricata-conf', CONF / 'suricata_ids.yaml', '--no-test', '--no-reload', '--force'])
    candidate = generated / 'suricata.rules'
    if not candidate.is_file() or not candidate.stat().st_size:
        raise ValueError('suricata-update no produjo reglas')
    # Harresi releases promise one rules file. Reject auxiliary files requiring
    # a multi-file deployment rather than install an incomplete release.
    if any(p.is_file() and p.name not in ('suricata.rules', 'classification.config') for p in generated.rglob('*')):
        raise ValueError('el paquete necesita ficheros auxiliares no admitidos por este flujo')
    return version, candidate, manifest


def validate(replacements, stage):
    for unit in UNITS:
        config = CONF / (unit + '.yaml')
        if not config.is_file():
            raise ValueError(f'falta el perfil real {config}; no se puede validar')
        data = yaml.safe_load(config.read_text())
        if data.get('include'):
            raise ValueError(f'{config}: includes requieren comprobación manual; no se promete una validación completa')
        base = Path(data.get('default-rule-path', MANAGED.parent))
        selected = set()
        parts = []
        for name in data.get('rule-files', []):
            pattern = str(Path(name) if Path(name).is_absolute() else base / name)
            # Managed replacements may not exist yet on a fresh installation.
            paths = [pattern] if Path(pattern).resolve() in replacements else glob.glob(pattern)
            if not paths:
                raise ValueError(f'{config}: no existe el fichero de reglas {pattern}')
            for source in paths:
                path = Path(source).resolve()
                selected.add(path)
                actual = replacements.get(path, path)
                if not actual.is_file():
                    raise ValueError(f'{config}: falta {actual}')
                parts.append(actual.read_bytes() + b'\n')
        if not set(replacements) <= selected:
            raise ValueError(f'{config}: el fichero que se cambia no está cargado en rule-files')
        bundle = stage / (unit + '.rules')
        bundle.write_bytes(b''.join(parts))
        logs = stage / (unit + '-validation')
        logs.mkdir(exist_ok=True)
        print(f'Validando configuración y todas las reglas de {unit}...', flush=True)
        run(['suricata', '-T', '-c', config, '-S', bundle, '-l', logs])


def command(unit, action):
    result = run(['suricatasc', SOCKETS / (unit + '-command.socket'), '-c', action], capture_output=True, text=True, timeout=60)
    try:
        reply = json.loads(result.stdout)
    except ValueError:
        reply = ast.literal_eval(result.stdout)
    if reply.get('return') != 'OK':
        raise ValueError(f'{unit}: {action}: {reply}')
    return reply.get('message')


def reload_running():
    failures = []
    runtime = Path(os.environ.get('HARRESI_RUNTIME_INTENT_FILE', '/run/harresi-services-runtime'))
    intended = None
    if runtime.exists():
        values = runtime.read_text().split()
        if len(values) != 2 or values[0] not in ('IDS', 'IDPS', 'stopped') or values[1] not in ('on', 'off'):
            raise ValueError('intención de ejecución no válida; no se recargaron reglas')
        intended = set()
        if values[0] == 'IDS': intended.add('suricata_ids')
        if values[0] == 'IDPS':
            intended.add('suricata_idps')
            if values[1] == 'on': intended.add('suricata_mitm')
    for unit in UNITS:
        if subprocess.run(['systemctl', 'is-active', '--quiet', unit]).returncode:
            continue
        if (intended is not None and unit not in intended) or (intended is None and subprocess.run(['systemctl', 'is-enabled', '--quiet', unit]).returncode):
            failures.append(f'{unit}: activo pero no seleccionado; reconcilie los servicios')
            continue
        try:
            command(unit, 'reload-rules')  # Blocking: completion is observable.
            stats = command(unit, 'ruleset-stats')
            if not isinstance(stats, dict) or int(stats.get('rules_failed', stats.get('failed', -1))) != 0:
                raise ValueError(f'{unit}: reglas fallidas o resultado no verificable: {stats}')
            print(f'{unit}: recarga completada sin reglas fallidas.', flush=True)
        except (ValueError, OSError, subprocess.SubprocessError, SyntaxError) as error:
            failures.append(str(error))
    if failures:
        raise ValueError('; '.join(failures))


def transaction(replacements, stage, metadata=None, restored_update=None):
    validate(replacements, stage)
    lock_path = Path(os.environ.get('HARRESI_SERVICE_LOCK', '/run/lock/harresi-services.lock'))
    lock_path.parent.mkdir(parents=True, exist_ok=True)
    with lock_path.open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        publish(replacements, stage, metadata, restored_update)


def publish(replacements, stage, metadata, restored_update):
    old = {path: path.read_bytes() if path.exists() else None for path in replacements}
    old_metadata = {path: path.read_bytes() if path.exists() else None for path in (UPDATE, STATE / 'state.json')}
    backup = stage / 'previous'
    backup.mkdir()
    if metadata is not None:
        previous = {'installed_version': read_state().get('installed_version', 'none'), 'files': {}}
        for path, content in old.items():
            filename = path.name
            if content is not None:
                (backup / filename).write_bytes(content)
            previous['files'][str(path)] = {'file': filename, 'sha512': hashlib.sha512(content).hexdigest() if content is not None else None}
        for path, content in old_metadata.items():
            if content is not None:
                (backup / path.name).write_bytes(content)
        (backup / 'snapshot.json').write_text(json.dumps(previous))
    try:
        for path, candidate in replacements.items():
            atomic(path, candidate.read_bytes())
        reload_running()
        if metadata is not None:
            if restored_update is not None:
                atomic(UPDATE, restored_update)
            else:
                update = yaml.safe_load(UPDATE.read_text()) if UPDATE.exists() else {}
                update = update or {}
                update['sources'] = [metadata['source']]
                # Fixed helper validates all profiles/reloads all selected instances.
                update.pop('test-command', None)
                update.pop('reload-command', None)
                atomic(UPDATE, yaml.safe_dump(update).encode())
            metadata['previous_version'] = read_state().get('installed_version', 'none')
            atomic(STATE / 'state.json', json.dumps(metadata, indent=2).encode() + b'\n')
            previous = STATE / 'previous'
            preserved = stage / 'previous-old'
            if previous.exists():
                shutil.copytree(previous, preserved)
                shutil.rmtree(previous)
            try:
                shutil.copytree(backup, previous)
            except BaseException:
                shutil.rmtree(previous, ignore_errors=True)
                if preserved.exists(): shutil.copytree(preserved, previous)
                raise
    except BaseException:
        for path, content in {**old, **old_metadata}.items():
            if content is None: path.unlink(missing_ok=True)
            else: atomic(path, content)
        try:
            reload_running()
        except BaseException as error:
            print(f'CRÍTICO: ficheros recuperados, pero la recarga anterior falló: {error}. Requiere recuperación del servicio.', file=sys.stderr)
            atomic(RECOVERY, b'Recarga de reglas restauradas pendiente; reinicie el modo desde el menu.\n')
            # A subset may have loaded the rejected candidate. Block transit
            # and intercepted HTTPS until recovery can verify every instance.
            subprocess.run(['iptables', '-w', '5', '-N', 'HARRESI_FAIL_CLOSED'], stderr=subprocess.DEVNULL)
            for arguments in (['-A', 'HARRESI_FAIL_CLOSED', '-j', 'DROP'],
                              ['-I', 'FORWARD', '1', '-m', 'comment', '--comment', 'harresi-suricata-fail-closed', '-j', 'HARRESI_FAIL_CLOSED'],
                              ['-I', 'INPUT', '1', '-p', 'tcp', '--dport', '8443', '-m', 'comment', '--comment', 'harresi-suricata-fail-closed', '-j', 'HARRESI_FAIL_CLOSED']):
                if subprocess.run(['iptables', '-w', '5', *arguments]).returncode:
                    print('CRÍTICO: no se pudo instalar la protección FAIL-CLOSED.', file=sys.stderr)
        print('ERROR: operación fallida; reglas y configuración anteriores recuperadas.', file=sys.stderr)
        raise


def main():
    if len(sys.argv) < 2:
        raise ValueError('uso: harresi-rules latest|list|check|status|install|rollback|next-sid|custom-apply|validate-output|reload')
    action = sys.argv[1]
    STATE.mkdir(parents=True, exist_ok=True, mode=0o750)
    with (STATE / '.lock').open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        if action == 'status':
            print(json.dumps(read_state(), indent=2)); return
        if action == 'next-sid':
            text = LOCAL.read_text() if LOCAL.exists() else ''
            print(max([8999999] + [int(s) for s in re.findall(r'\bsid:\s*(\d+)', text)]) + 1); return
        with tempfile.TemporaryDirectory(prefix='.stage-', dir=STATE) as temporary:
            stage = Path(temporary)
            if action == 'reload':
                reload_running(); print('OK: todas las instancias seleccionadas activas recargadas.'); return
            if action == 'validate-output':
                if len(sys.argv) != 3: raise ValueError('uso: harresi-rules validate-output <file>')
                validate({MANAGED.resolve(): Path(sys.argv[2])}, stage)
                print('OK: salida validada con los tres perfiles reales.'); return
            if action in ('latest', 'list'):
                file = stage / 'remote'
                download(REPO + ('/latest.json' if action == 'latest' else '/releases.txt'), file)
                print(file.read_text(), end=''); return
            if action in ('check', 'install'):
                version, candidate, manifest = release(sys.argv[2] if len(sys.argv) > 2 else 'latest', stage)
                replacements = {MANAGED.resolve(): candidate}
                if action == 'check':
                    validate(replacements, stage)
                    print(f'OK: {version} validada; no se instaló.'); return
                metadata = {'installed_version': version, 'installed_at': datetime.datetime.now(datetime.timezone.utc).isoformat(),
                            'source': f'{REPO}/releases/{version}/{manifest["artifact"]}', 'sha512': manifest['sha512']}
                transaction(replacements, stage, metadata)
                print(f'OK: versión {version} guardada y aplicada a las instancias activas.'); return
            if action == 'custom-apply':
                if len(sys.argv) != 3: raise ValueError('uso: harresi-rules custom-apply <file>')
                source = Path(sys.argv[2])
                if not source.is_file(): raise ValueError(f'no existe {source}')
                candidate = stage / 'local.rules'
                candidate.write_bytes((LOCAL.read_bytes() if LOCAL.exists() else b'') + b'\n' + source.read_bytes() + b'\n')
                transaction({LOCAL.resolve(): candidate}, stage)
                print('OK: reglas personalizadas guardadas y aplicadas; las instancias detenidas las cargarán al iniciar.'); return
            if action == 'rollback':
                previous = STATE / 'previous'
                if not (previous / 'snapshot.json').exists(): raise ValueError('no hay copia local anterior para recuperar')
                snapshot = json.loads((previous / 'snapshot.json').read_text())
                replacements = {}
                for path, info in snapshot['files'].items():
                    if Path(path).resolve() != MANAGED.resolve(): raise ValueError('copia anterior no válida')
                    file = previous / info['file']
                    if info['sha512'] is None or hashlib.sha512(file.read_bytes()).hexdigest() != info['sha512']:
                        raise ValueError('copia anterior ausente o checksum no válido')
                    copy = stage / info['file']; shutil.copyfile(file, copy); replacements[Path(path)] = copy
                metadata = json.loads((previous / 'state.json').read_text()) if (previous / 'state.json').exists() else {'installed_version': snapshot['installed_version'], 'source': REPO}
                metadata['installed_at'] = datetime.datetime.now(datetime.timezone.utc).isoformat()
                metadata['restored_from'] = 'local-backup'
                restored_update = (previous / 'update.yaml').read_bytes() if (previous / 'update.yaml').exists() else None
                transaction(replacements, stage, metadata, restored_update)
                print('OK: versión anterior recuperada desde la copia local, validada y recargada.'); return
            raise ValueError('operación no válida')


if __name__ == '__main__':
    os.umask(0o027)
    try:
        main()
    except (ValueError, OSError, KeyError, yaml.YAMLError, subprocess.SubprocessError, tarfile.TarError) as error:
        print(f'ERROR: {error}', file=sys.stderr)
        sys.exit(1)
