#!/usr/bin/env python3
"""Deploy only web/, preserving server-owned data. Passwords never enter argv."""
import os
from pathlib import Path
import subprocess
import sys
from urllib.parse import urlsplit

ROOT = Path(__file__).resolve().parents[1]

def quoted(value):
    if any(c in value for c in '\r\n\x00'):
        raise ValueError('Deployment variables must not contain line breaks or NUL bytes.')
    return '"' + value.replace('\\', '\\\\').replace('"', '\\"') + '"'

def deployment_commands(environ, webroot):
    for key in ['timftphost', 'timftpuser', 'timftppassword', 'projectftp']:
        if not environ.get(key):
            raise ValueError(f'CI variable {key} is not set.')
    host = environ['timftphost']
    if '://' not in host:
        host = 'ftp://' + host
    parsed = urlsplit(host)
    if parsed.scheme not in ['ftp', 'ftps', 'sftp'] or not parsed.hostname:
        raise ValueError('timftphost must be an FTP, FTPS or SFTP host URL.')
    if parsed.username or parsed.password or parsed.query or parsed.fragment:
        raise ValueError('Keep login credentials in timftpuser/timftppassword; use a plain host URL.')
    commands = [
        'set cmd:fail-exit yes',
        'set net:timeout 20',
        'set net:max-retries 2',
        'set net:reconnect-interval-base 3',
        # This hosting account uses a mismatched FTP certificate; retain the owner's deployment policy.
        'set ssl:verify-certificate no',
        'set ftp:list-options -a',
        # New SFTP hosts are remembered within this runner; changed host keys fail.
        'set sftp:connect-program "ssh -a -x -o StrictHostKeyChecking=accept-new"',
        f'open --user {quoted(environ["timftpuser"])} --env-password {quoted(host)}',
        f'cd {quoted(environ["projectftp"])}',
        'mkdir -p data || echo "Using existing data directory"',
        f'put {quoted(str(webroot / "data/.htaccess"))} -o data/.htaccess',
        # No --delete-excluded: these paths belong to the running server.
        'mirror --reverse --delete --no-perms --no-symlinks --max-errors=1 '
        '--exclude-glob "data/" --exclude-glob "data/**" '
        '--exclude-glob "tests/" --exclude-glob "tests/**" '
        '--exclude-glob "README.md" --exclude-glob "router.php" '
        f'{quoted(str(webroot))} .',
        'bye',
    ]
    return '\n'.join(commands) + '\n'

def write_asset_version(webroot, environ=None):
    """Stamp the deploy commit into web/asset-version.txt for cache-busting."""
    environ = os.environ if environ is None else environ
    sha = (environ.get('CI_COMMIT_SHA') or '').strip()
    if not sha:
        try:
            sha = subprocess.check_output(
                ['git', '-C', str(ROOT), 'rev-parse', 'HEAD'], text=True, stderr=subprocess.DEVNULL
            ).strip()
        except (subprocess.CalledProcessError, FileNotFoundError):
            sha = ''
    if not sha or len(sha) < 7:
        raise ValueError('Unable to determine commit SHA for asset-version.txt (set CI_COMMIT_SHA).')
    (webroot / 'asset-version.txt').write_text(sha + '\n', encoding='utf-8')
    print(f'Wrote asset-version.txt = {sha}')

def main():
    try:
        webroot = ROOT / 'web'
        write_asset_version(webroot, os.environ)
        commands = deployment_commands(os.environ, webroot)
        subprocess.run(['lftp', '--norc'], input=commands, text=True,
                       env={**os.environ, 'LFTP_PASSWORD':os.environ['timftppassword']}, check=True)
    except (ValueError, subprocess.CalledProcessError) as error:
        print(str(error), file=sys.stderr)
        return 1
    return 0

if __name__ == '__main__':
    sys.exit(main())
