#!/usr/bin/env python3
"""CAC application file backup. Python 3.7+, GNU tar; preview by default."""
import argparse
import datetime
import fcntl
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import time
import uuid

FORMAT = 'cac-appfiles-v1'
DESTINATION = Path('/workspace/app-backups')
EXCLUDES = ('data/apps/foodsafe1/aiboxfile', 'data/apps/foodsafe2/aiboxfile')
REQUIRED = (
    'data/apps/foodsafe1', 'data/apps/foodsafe2', 'data/apps/front1', 'data/apps/front2',
    'etc/nginx', 'opt/zhct-php73/etc', 'opt/zhct-redis627/etc',
    'etc/systemd/system', 'var/lib/foodsafe/.pm2/dump.pm2',
    'usr/local/lib/foodsafe-maintenance', 'etc/mosquitto',
)
REQUIRED_FILES = (
    'data/apps/foodsafe1/services/gateway-service/.env',
    'data/apps/foodsafe2/services/gateway-service/.env',
    'data/apps/front1/private/front1.env', 'data/apps/front2/private/front2.env',
    'etc/nginx/conf.d/foodsafe-release-1.conf', 'etc/nginx/conf.d/foodsafe-release-2.conf',
    'etc/nginx/conf.d/zhct-front1.conf', 'etc/nginx/conf.d/zhct-front2.conf',
    'opt/zhct-php73/etc/php.ini', 'opt/zhct-php73/etc/php-fpm.conf',
    'opt/zhct-redis627/etc/redis.conf', 'etc/mosquitto/mosquitto.conf', 'etc/mosquitto/passwd',
)
OPTIONAL = (
    'usr/lib/systemd/system', 'etc/firewalld', 'etc/sysctl.conf', 'etc/sysctl.d',
    'var/lib/foodsafe-maintenance',
)
NAME = re.compile(r'^appfiles-\d{8}-\d{6}-\d{6}-[0-9a-f]{8}$')


def digest(path):
    result = hashlib.sha256()
    with path.open('rb') as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b''):
            result.update(block)
    return result.hexdigest()


def secure_directory(path):
    for item in [path] + list(path.parents):
        if item.is_symlink():
            raise RuntimeError('备份目录及父目录不能是软链接：' + str(item))
    path.mkdir(mode=0o700, parents=True, exist_ok=True)
    if not path.is_dir() or path.stat().st_uid != os.geteuid() or path.stat().st_mode & 0o077:
        raise RuntimeError('备份目录必须属于当前root用户且权限为0700：' + str(path))


def run_tar(root, archive, sources, error_log):
    command = ['tar', '--create', '--gzip', '--file=' + str(archive),
               '--numeric-owner', '--acls', '--xattrs', '--selinux', '--anchored']
    command += ['--exclude=' + name for name in EXCLUDES]
    command += ['--directory=' + str(root), '--'] + list(sources)
    with error_log.open('wb') as errors:
        result = subprocess.run(command, stderr=errors)
    if result.returncode != 0:
        raise RuntimeError('tar备份失败（含源文件变化），退出码{}；保留未完成目录供检查'.format(result.returncode))


def verify_archive(archive, sources):
    subprocess.run(['gzip', '-t', str(archive)], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
    seen = set()
    error = False
    with (archive.parent / 'verify.stderr').open('wb') as errors:
        process = subprocess.Popen(['tar', '--list', '--gzip', '--file=' + str(archive)],
                                   stdout=subprocess.PIPE, stderr=errors, universal_newlines=True)
        for line in process.stdout:
            name = line.rstrip('\n').rstrip('/')
            seen.add(name)
            if name.startswith('/') or '..' in name.split('/') or any(
                    name == value or name.startswith(value + '/') for value in EXCLUDES):
                error = True
        process.stdout.close()
        code = process.wait()
    if code or error or not set(sources).issubset(seen):
        raise RuntimeError('压缩包目录校验失败；不发布本轮备份，不清理旧备份')


def is_complete(path):
    if path.is_symlink() or not path.is_dir() or not NAME.fullmatch(path.name):
        return False
    try:
        files = ('manifest.json', 'files.tar.gz', 'SHA256SUMS')
        if any((path / name).is_symlink() or not (path / name).is_file() for name in files):
            return False
        expected = (path / 'SHA256SUMS').read_text().splitlines()
        if '{}  manifest.json'.format(digest(path / 'manifest.json')) not in expected:
            return False
        if not any(re.fullmatch(r'[0-9a-f]{64}  files\.tar\.gz', line) for line in expected):
            return False
        data = json.loads((path / 'manifest.json').read_text())
        return (data.get('format') == FORMAT and data.get('verified') is True
                and data.get('archive_bytes') == (path / 'files.tar.gz').stat().st_size
                and data.get('directory') == path.name)
    except (OSError, ValueError):
        return False


def create_backup(root, destination, sources, metadata, keep):
    if not 1 <= keep <= 30:
        raise RuntimeError('保留份数必须在1到30之间')
    secure_directory(destination)
    for name in metadata:
        if Path(name).name != name or name in ('', '.', '..'):
            raise RuntimeError('非法元数据文件名')
    stamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S-%f')
    name = 'appfiles-' + stamp + '-' + uuid.uuid4().hex[:8]
    stage = destination / ('.incomplete-' + name)
    stage.mkdir(mode=0o700)
    # umask also applies when these functions are called outside the CLI.
    old_umask = os.umask(0o077)
    try:
        (stage / 'metadata').mkdir(mode=0o700)
        for key, value in metadata.items():
            (stage / 'metadata' / key).write_bytes(value)
        archive = stage / 'files.tar.gz'
        run_tar(root, archive, sources, stage / 'tar.stderr')
        verify_archive(archive, sources)
        manifest = {
            'format': FORMAT, 'directory': name, 'verified': True,
            'created_local': datetime.datetime.now().astimezone().isoformat(),
            'sources': ['/' + item for item in sources],
            'excluded': ['/' + item for item in EXCLUDES],
            'archive_bytes': archive.stat().st_size, 'keep_successful_copies': keep,
            'consistency': 'live file backup, not an atomic database or machine snapshot',
        }
        (stage / 'manifest.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + '\n')
        checks = []
        for item in sorted(stage.rglob('*')):
            if item.is_file():
                checks.append('{}  {}'.format(digest(item), item.relative_to(stage).as_posix()))
        (stage / 'SHA256SUMS').write_text('\n'.join(checks) + '\n')
        subprocess.run(['sha256sum', '-c', 'SHA256SUMS'], cwd=str(stage), check=True,
                       stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
        stage.rename(destination / name)
        complete = sorted((item for item in destination.iterdir() if is_complete(item)), key=lambda item: item.name)
        for old in complete[:-keep]:
            shutil.rmtree(str(old))  # Only recognized completed backup folders, after current verification.
        return destination / name
    finally:
        os.umask(old_umask)


def preflight():
    if os.geteuid() != 0:
        raise RuntimeError('请在新服务器root终端执行')
    for executable in ('tar', 'gzip', 'sha256sum', 'du', 'crontab'):
        if not shutil.which(executable):
            raise RuntimeError('缺少命令：' + executable)
    version = subprocess.check_output(['tar', '--version']).decode('utf-8', 'replace')
    if 'GNU tar' not in version:
        raise RuntimeError('本脚本需要GNU tar')
    for name in REQUIRED + REQUIRED_FILES:
        if not Path('/' + name).exists():
            raise RuntimeError('必要路径不存在：/' + name)
    for name in REQUIRED:
        if Path('/' + name).is_symlink():
            raise RuntimeError('必要源目录为软链接，需先核对实际目标：/' + name)
    optional = [name for name in OPTIONAL if Path('/' + name).exists()]
    sources = list(REQUIRED) + optional
    # Ensure the backup destination cannot recurse into source directories.
    for name in sources:
        if str(DESTINATION).startswith('/' + name + '/'):
            raise RuntimeError('备份输出目录不能位于源目录内')
    cron = subprocess.run(['crontab', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                          env=dict(os.environ, LC_ALL='C'))
    if cron.returncode and not (cron.returncode == 1 and b'no crontab for' in cron.stderr):
        raise RuntimeError('读取root crontab失败')
    command = ['du', '-sc', '-B1'] + ['--exclude=/' + name for name in EXCLUDES]
    size_output = subprocess.check_output(command + ['/' + name for name in sources])
    size = int(size_output.splitlines()[-1].split()[0])
    ancestor = DESTINATION
    while not ancestor.exists():
        ancestor = ancestor.parent
    if shutil.disk_usage(str(ancestor)).free < size + max(1024 ** 3, size // 10):
        raise RuntimeError('剩余空间不足以安全生成新备份；不先删除旧备份腾空间')
    return sources, {'root.crontab': cron.stdout}, size


def main():
    parser = argparse.ArgumentParser(description='四套应用文件备份；默认只预览，--apply实际备份')
    parser.add_argument('--apply', action='store_true')
    parser.add_argument('--keep', type=int, default=7, choices=range(1, 31), metavar='1..30')
    args = parser.parse_args()
    os.environ['TZ'] = 'Asia/Shanghai'
    os.environ['LC_ALL'] = 'C.UTF-8'
    time.tzset()
    sources, metadata, size = preflight()
    print(json.dumps({'mode': 'apply' if args.apply else 'preview', 'source_bytes': size,
                      'destination': str(DESTINATION), 'keep_successful_copies': args.keep,
                      'excluded': ['/' + name for name in EXCLUDES],
                      'optional_missing': ['/' + name for name in OPTIONAL if name not in sources]}, ensure_ascii=False), flush=True)
    if not args.apply:
        print('预览完成；没有生成备份，没有清理旧备份，没有修改crontab')
        return
    old_umask = os.umask(0o077)
    try:
        secure_directory(DESTINATION)
        lock_path = DESTINATION / '.backup.lock'
        if lock_path.is_symlink():
            raise RuntimeError('锁文件不能是软链接')
        with lock_path.open('a') as lock:
            try:
                fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except BlockingIOError:
                raise RuntimeError('已有备份正在运行，本次退出')
            result = create_backup(Path('/'), DESTINATION, sources, metadata, args.keep)
        print(json.dumps({'backed_up': True, 'verified': True, 'directory': str(result),
                          'archive_bytes': (result / 'files.tar.gz').stat().st_size}, ensure_ascii=False))
    finally:
        os.umask(old_umask)


if __name__ == '__main__':
    try:
        main()
    except Exception as error:
        print('备份未成功完成：' + str(error), file=sys.stderr)
        sys.exit(1)
