#!/usr/bin/env python3
"""Manual: upload throwaway probe dirs _vbprobe_N/ (one .htaccess directive each + index.html)
next to the project, fetch them over HTTP, then remove ONLY those probe dirs. Never touches the project."""
import os, subprocess, sys, tempfile, urllib.request, urllib.error
from pathlib import Path
from urllib.parse import urlsplit
sys.path.insert(0, str(Path(__file__).resolve().parent))
from deploy_guard import project_dir  # noqa: E402
from deploy import quoted  # noqa: E402

PROBES = {
    'none': '',
    'options': 'Options -Indexes',
    'dirindex': 'DirectoryIndex index.php',
    'rewrite': '<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteCond %{HTTP:Authorization} .\nRewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\n</IfModule>',
    'setenvif': '<IfModule mod_setenvif.c>\nSetEnvIf Authorization "(.+)" HTTP_AUTHORIZATION=$1\n</IfModule>',
    'require': '<FilesMatch "^(README\\.md|router\\.php)$">\nRequire all denied\n</FilesMatch>',
    'header': '<IfModule mod_headers.c>\nHeader always set X-Content-Type-Options "nosniff"\n</IfModule>',
    'addtype': '<IfModule mod_mime.c>\nAddType application/manifest+json .webmanifest\n</IfModule>',
    'full': (Path(__file__).resolve().parents[1] / 'web/.htaccess').read_text(),
}

def lftp(e, host, cmds):
    return subprocess.run(['lftp', '--norc'], input='\n'.join(cmds) + '\nbye\n', text=True, capture_output=True,
                          env={**e, 'LFTP_PASSWORD': e['timftppassword']})

def main():
    e = os.environ
    parent = os.path.dirname(project_dir(e).rstrip('/')) or '.'
    host = e['timftphost'] if '://' in e['timftphost'] else 'ftp://' + e['timftphost']
    pre = ['set net:timeout 20', 'set ssl:verify-certificate no',
           'set sftp:connect-program "ssh -a -x -o StrictHostKeyChecking=accept-new"',
           f'open --user {quoted(e["timftpuser"])} --env-password {quoted(host)}', f'cd {quoted(parent)}']
    tmp = Path(tempfile.mkdtemp())
    cmds = list(pre)
    for name, body in PROBES.items():
        d = tmp / f'_vbprobe_{name}'; d.mkdir()
        (d / 'index.html').write_text('ok\n')
        if body: (d / '.htaccess').write_text(body + '\n')
        cmds.append(f'mirror --reverse --no-perms {quoted(str(d))} {quoted(d.name)}')
    r = lftp(e, host, cmds); print('upload rc', r.returncode, r.stderr.replace(e['timftppassword'], '***')[-500:])
    try:
        for name in PROBES:
            url = f'https://projects.timfalken.com/_vbprobe_{name}/index.html'
            try: code = urllib.request.urlopen(url, timeout=20).status
            except urllib.error.HTTPError as x: code = x.code
            print(f'PROBE {name:10s} {code}')
    finally:
        r = lftp(e, host, pre + [f'rm -rf {quoted("_vbprobe_" + n)}' for n in PROBES])
        print('cleanup rc', r.returncode)
    return 0

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