#!/usr/bin/env python3
"""Offline, guarded patch. Default is read-only; --apply installs both instances."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import tempfile
import time

HERE = Path(__file__).resolve().parent
REL = Path('services/gateway-service/dist/services/gateway-service/src/modules/sampling.controller.js')
OLD_SHA = '53fcdeb5f391a8432dbf9114c9be65b1f8cdb61de743e1fceb70a914d3fd31e1'
NGINX = '/usr/sbin/nginx'
BACKUPS = Path('/var/backups/foodsafe-image-port')


def sha(data):
    return hashlib.sha256(data).hexdigest()


def regular(path):
    for part in [path] + list(path.parents):
        if part.is_symlink():
            raise RuntimeError('拒绝符号链接: ' + str(part))
    if not path.is_file():
        raise RuntimeError('文件不存在: ' + str(path))


def patch_nginx(data, instance):
    text = data.decode('utf-8')
    upstream = 'foodsafe_release_' + str(instance)
    if not re.search(r'upstream\s+' + upstream + r'\s*\{', text):
        raise RuntimeError('Nginx实例标识不匹配')
    found = []

    def location(match):
        block = match.group()
        if not re.search(r'proxy_pass\s+http://' + upstream + r'(?:/|;)', block):
            return block  # Preserve the front-desk integration Host policy.
        headers = re.findall(r'proxy_set_header\s+Host\s+(\$host|\$http_host)\s*;', block)
        if len(headers) != 1:
            raise RuntimeError('后端代理Host配置无法唯一确认')
        found.append(headers[0])
        return re.sub(r'(proxy_set_header\s+Host\s+)\$host(\s*;)', r'\1$http_host\2', block)

    changed = re.sub(r'\blocation\b[^{}]*\{[^{}]*\}', location, text)
    if not found:
        raise RuntimeError('未找到可验证的食安后端代理')
    return changed.encode('utf-8')


def plan(app_roots, config_paths, payload):
    new_sha = sha(payload)
    expected = json.loads((HERE / 'payload.json').read_text())['sha256']
    if new_sha != expected:
        raise RuntimeError('补丁文件SHA256校验失败')
    entries = []
    for instance, root, active in zip((1, 2), app_roots, config_paths):
        code = root / REL
        for path in [code, active, root / 'deploy/nginx.conf']:
            regular(path)
            old = path.read_bytes()
            if path == code:
                if sha(old) not in (OLD_SHA, new_sha):
                    raise RuntimeError('后端版本与已验证基线不符: ' + str(path))
                new = payload
            else:
                new = patch_nginx(old, instance)
            if old != new:
                meta = path.stat()
                entries.append(dict(path=str(path), old=old, new=new,
                                    uid=meta.st_uid, gid=meta.st_gid,
                                    mode=stat.S_IMODE(meta.st_mode)))
    return entries


def atomic(path, data, entry):
    fd, temp = tempfile.mkstemp(prefix='.foodsafe-image-port-', dir=str(path.parent))
    try:
        with os.fdopen(fd, 'wb') as handle:
            handle.write(data)
            handle.flush()
            os.fsync(handle.fileno())
            os.fchmod(handle.fileno(), entry['mode'])
            if os.geteuid() == 0:
                os.fchown(handle.fileno(), entry['uid'], entry['gid'])
        os.replace(temp, str(path))
    finally:
        if os.path.exists(temp):
            os.unlink(temp)


def run(args):
    subprocess.run(args, check=True, timeout=30, stdout=subprocess.PIPE, stderr=subprocess.PIPE)


def restart():
    for instance in (1, 2):
        run(['/usr/sbin/runuser', '-u', 'foodsafe', '--', '/usr/bin/env',
             'HOME=/var/lib/foodsafe', 'PM2_HOME=/var/lib/foodsafe/.pm2',
             'PATH=/opt/foodsafe-node/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
             '/opt/foodsafe-node/bin/pm2', 'restart', 'foodsafe-' + str(instance)])
        for attempt in range(15):
            try:
                run(['/usr/bin/curl', '--noproxy', '*', '-fsS', '--connect-timeout', '2',
                     '--max-time', '3', 'http://127.0.0.1:420' + str(instance) + '/api/health'])
                break
            except subprocess.CalledProcessError:
                if attempt == 14:
                    raise RuntimeError('实例健康检查未恢复: ' + str(instance))
                time.sleep(1)


def activate():
    run([NGINX, '-t'])
    run(['/usr/bin/systemctl', 'reload', 'nginx'])
    restart()


def install(entries, backup_root=BACKUPS):
    if not entries:
        print('两套均已修复，无需修改或重启')
        return None
    run([NGINX, '-t'])
    if backup_root.is_symlink():
        raise RuntimeError('备份根目录不能为符号链接')
    backup_root.mkdir(parents=True, mode=0o700, exist_ok=True)
    backup = Path(tempfile.mkdtemp(prefix='patch-', dir=str(backup_root)))
    manifest = []
    for index, entry in enumerate(entries):
        original = backup / (str(index) + '.original')
        original.write_bytes(entry['old'])
        original.chmod(0o600)
        manifest.append({k: entry[k] for k in ('path', 'mode', 'uid', 'gid')})
        manifest[-1].update(backup=original.name, old_sha=sha(entry['old']), new_sha=sha(entry['new']))
    (backup / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
    written = []
    try:
        for entry in entries:
            path = Path(entry['path'])
            regular(path)
            if path.read_bytes() != entry['old']:
                raise RuntimeError('安装期间文件发生变更: ' + str(path))
            atomic(path, entry['new'], entry)
            written.append(entry)
        activate()
    except BaseException:
        # Do not overwrite any concurrent changes during recovery.
        for entry in written:
            if Path(entry['path']).read_bytes() != entry['new']:
                raise RuntimeError('检测到并发改动，保留备份供人工恢复: ' + str(backup))
        for entry in reversed(written):
            atomic(Path(entry['path']), entry['old'], entry)
        if written:
            try:
                activate()
            except BaseException:
                raise RuntimeError('已恢复原文件，服务恢复失败，请检查；备份: ' + str(backup))
        raise RuntimeError('安装失败，原文件及服务已恢复；备份: ' + str(backup))
    print('已安装。回退清单: ' + str(backup / 'manifest.json'))
    return backup / 'manifest.json'


def rollback(manifest_path):
    regular(manifest_path)
    entries = json.loads(manifest_path.read_text())
    allowed = {str(Path('/data/apps/foodsafe' + str(i)) / rel)
               for i in (1, 2) for rel in (REL, Path('deploy/nginx.conf'))}
    allowed.update('/etc/nginx/conf.d/foodsafe-release-' + str(i) + '.conf' for i in (1, 2))
    prepared = []
    for entry in entries:
        target = Path(entry['path'])
        original = manifest_path.parent / entry['backup']
        if str(target) not in allowed or original.parent != manifest_path.parent:
            raise RuntimeError('回退路径不在本补丁范围')
        regular(target)
        regular(original)
        old = original.read_bytes()
        if sha(old) != entry['old_sha'] or sha(target.read_bytes()) not in (entry['old_sha'], entry['new_sha']):
            raise RuntimeError('回退SHA不匹配，保留现场: ' + str(target))
        prepared.append((target, old, entry))
    for target, old, entry in prepared:
        atomic(target, old, entry)
    activate()
    print('已按本次清单恢复原文件及服务')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    mode = parser.add_mutually_exclusive_group()
    mode.add_argument('--apply', action='store_true')
    mode.add_argument('--rollback', type=Path)
    args = parser.parse_args()
    try:
        if args.apply or args.rollback:
            if os.geteuid() != 0:
                raise RuntimeError('实际安装或回退需使用root')
        if args.rollback:
            rollback(args.rollback)
        else:
            entries = plan([Path('/data/apps/foodsafe1'), Path('/data/apps/foodsafe2')],
                           [Path('/etc/nginx/conf.d/foodsafe-release-1.conf'),
                            Path('/etc/nginx/conf.d/foodsafe-release-2.conf')],
                           (HERE / 'sampling.controller.js').read_bytes())
            for entry in entries:
                print('待更新: ' + entry['path'])
            if args.apply:
                install(entries)
            else:
                print('只读预检通过；使用 --apply 安装，当前未修改文件')
    except Exception as error:
        if isinstance(error, subprocess.SubprocessError):
            raise SystemExit('补丁停止：系统命令失败。请现场检查Nginx/PM2/健康接口，未输出原始日志以免泄露私有配置。')
        raise SystemExit('补丁停止：' + str(error))
