#!/usr/bin/python3
"""Privileged Plesk transfer worker. Only fixed commands, HTTPS origin and storage paths."""
import base64
import fcntl
import hashlib
import http.client
import json
import os
import re
import secrets
import shutil
import smtplib
import sqlite3
import ssl
import subprocess
import sys
import tempfile
import time
import zipfile
from xml.etree import ElementTree
from datetime import datetime, timezone
from email.headerregistry import Address
from email.message import EmailMessage
from email.utils import format_datetime
from html import escape
from pathlib import Path

ROOT = Path('/var/lib/ezfileshare-plesk')
HOST = 'ezfileshare.io'
PLESK = '/usr/sbin/plesk'
SHARE_ID = re.compile(r'[A-Za-z0-9]{8}(?:[A-Za-z0-9]{2})?')
FILE_ID = re.compile(r'[A-Za-z0-9]{8}')
LINK_PREFIX = r'https://ezfileshare\.io/s/(' + SHARE_ID.pattern + ')'
LINK = re.compile(LINK_PREFIX + r'#plesk-v1\.([a-f0-9]{64})\.([a-f0-9]{64})(?:\.([A-Za-z0-9_-]{1,2048}))?')
RAW_LINK = re.compile(LINK_PREFIX + r'#plesk-v2\.([a-f0-9]{64})\.([A-Za-z0-9_-]{1,2048})')
GUID = re.compile(r'[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}')
MAILBOX = re.compile(r"[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9.-]+")
BLOCK = 1024 * 1024


def fail(message):
    raise ValueError(message)


def command(args, *, secret=None, env=None, capture=False, message=None):
    result = subprocess.run(args, input=secret, stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
                            stderr=subprocess.PIPE, env=env)
    if result.returncode:
        fail(message or (Path(args[0]).name + ' failed (exit %d).' % result.returncode))
    return result.stdout


def db(inventory, statement):
    result = subprocess.run([PLESK, 'db', '-N', '-B', '-e', statement], capture_output=True)
    if result.returncode:
        # Report the database error number without exposing query values or credentials.
        error = re.search(rb'\bERROR (\d+)\b', result.stderr)
        detail = 'database error ' + error[1].decode() if error else 'exit %d' % result.returncode
        fail('Could not read Plesk %s (%s).' % (inventory, detail))
    return [line.split('\t') for line in result.stdout.decode().splitlines()]


def subscriptions():
    return db('subscriptions', 'SELECT d.id,d.guid,d.name,c.email,d.status FROM domains d '
              'JOIN clients c ON c.id=d.cl_id WHERE d.webspace_id=0 AND d.parentDomainId=0 ORDER BY d.name')


def snapshot(target):
    rows = [r for r in subscriptions() if r[1] == target]
    if len(rows) != 1:
        fail('The selected subscription no longer exists.')
    ident, guid, name, owner, status = rows[0]
    scope = 'SELECT id FROM domains WHERE id={0} OR webspace_id={0}'.format(int(ident))
    hosts = db('sites', 'SELECT id,name FROM domains WHERE id IN (' + scope + ') ORDER BY id')
    aliases = db('domain aliases', 'SELECT id,name FROM domain_aliases WHERE dom_id IN (' + scope + ') ORDER BY id')
    databases = db('databases', 'SELECT id,name FROM data_bases WHERE dom_id IN (' + scope + ') ORDER BY id')
    mail = db('mail accounts', 'SELECT id,mail_name,dom_id FROM mail WHERE dom_id IN (' + scope + ') ORDER BY id')
    if not MAILBOX.fullmatch(owner):
        fail('Configure a valid owner email in Plesk before exporting.')
    if owner.rsplit('@', 1)[1].lower() in {r[1].lower() for r in hosts + aliases}:
        fail('The owner mailbox is on a domain being removed. Update the Plesk owner contact first.')
    return dict(id=int(ident), guid=guid, domain=name, owner=owner, status=int(status),
                sites=hosts, aliases=aliases, databases=databases, mail=mail)


def request(method, path, body=None, headers=None, stream=None):
    conn = http.client.HTTPSConnection(HOST, timeout=600)
    try:
        conn.request(method, path, body=body, headers=headers or {})
        response = conn.getresponse()
        if response.status // 100 != 2:
            fail('ezfileshare returned HTTP %d.' % response.status)
        if stream is not None:
            return stream(response)
        payload = response.read(2 * BLOCK + 1)
        if len(payload) > 2 * BLOCK:
            fail('Unexpected service response size.')
        return json.loads(payload) if payload else None
    finally:
        conn.close()


def copy_digest(source, expected, output=None):
    size = 0
    digest = hashlib.sha256()
    while True:
        chunk = source.read(BLOCK)
        if not chunk:
            break
        size += len(chunk)
        if size > expected:
            fail('Archive exceeds declared size.')
        digest.update(chunk)
        if output is not None:
            output.write(chunk)
    if size != expected:
        fail('Archive is incomplete.')
    return digest.hexdigest()


def checked_id(value, pattern):
    if not isinstance(value, str) or not pattern.fullmatch(value):
        fail('Invalid identifier in service response.')
    return value


def gpg(source, destination, key, work):
    home = work / 'gnupg'
    home.mkdir(mode=0o700, exist_ok=True)
    args = ['/usr/bin/gpg', '--homedir', str(home), '--batch', '--pinentry-mode', 'loopback',
            '--passphrase-fd', '0', '--output', str(destination)]
    args += ['--max-output', str(source.stat().st_size), '--decrypt']
    command(args + [str(source)], secret=(key + '\n').encode())


def upload(path):
    size = path.stat().st_size
    spec = {'files': [{'name': path.name, 'size': size}], 'expires_in_days': 7}
    created = request('POST', '/api/shares', json.dumps(spec), {'Content-Type': 'application/json'})
    sid = checked_id(created['id'], SHARE_ID)
    fid = checked_id(created['files'][0]['id'], FILE_ID)
    resource = '/api/shares/' + sid
    url = resource + '/files/' + fid
    auth = {'X-Upload-Token': created['token']}
    with path.open('rb') as data:
        checksum = copy_digest(data, size)
        data.seek(0)
        request('PUT', url, data, {**auth, 'Content-Length': str(size), 'Content-Type': 'application/octet-stream'})
    deadline = time.monotonic() + 7200
    while time.monotonic() < deadline:
        progress = request('GET', resource + '/progress', headers=auth)
        if progress['ready']:
            break
        if any(f['status'] in ('error', 'infected') for f in progress['files']):
            fail('ezfileshare rejected the archive.')
        time.sleep(3)
    else:
        fail('Timed out waiting for publication.')
    if request('GET', url, stream=lambda r: copy_digest(r, size)) != checksum:
        fail('Published archive checksum differs from the original.')
    return sid, fid, checksum, request('GET', resource)['expires_at'], created['management_token']


def smtp_settings():
    path = ROOT / 'smtp.json'
    try:
        return json.loads(path.read_text())
    except FileNotFoundError:
        return {}


def save_smtp():
    settings = json.loads(sys.stdin.read(16384))
    host = settings['host'].strip()
    bcc_logged_in = settings.get('bcc_logged_in') is True
    if not host:
        write_private_json(ROOT / 'smtp.json', {'bcc_logged_in': bcc_logged_in})
        return
    port = settings['port']
    tls = settings['tls']
    sender = settings['sender'].strip()
    sender_name = settings.get('sender_name', '')
    if not isinstance(sender_name, str) or re.search(r'[\x00-\x1f\x7f]', sender_name):
        fail('Enter a sender name on a single line.')
    sender_name = sender_name.strip()
    if len(sender_name) > 120:
        fail('Sender name must be 120 characters or fewer.')
    username = settings['username'].strip()
    password = settings['password']
    if not re.fullmatch(r'[A-Za-z0-9.:-]{1,253}', host):
        fail('Enter an SMTP hostname or IP address without a URL or port.')
    if not re.fullmatch(r'[0-9]{1,5}', port) or not 1 <= int(port) <= 65535:
        fail('Enter an SMTP port from 1 to 65535.')
    if tls not in ('starttls', 'implicit', 'plaintext'):
        fail('Select STARTTLS, implicit TLS or plaintext SMTP.')
    if not MAILBOX.fullmatch(sender):
        fail('Enter a single SMTP sender email address.')
    previous = smtp_settings()
    if not password and username and (previous.get('username'), previous.get('host')) == (username, host):
        password = previous['password']
    if bool(username) != bool(password):
        fail('SMTP authentication requires both a username and a password.')
    with tempfile.NamedTemporaryFile(mode='w', dir=ROOT, delete=False) as pending:
        json.dump(dict(host=host, port=int(port), tls=tls, sender=sender, sender_name=sender_name,
                       username=username, password=password, bcc_logged_in=bcc_logged_in), pending)
    Path(pending.name).replace(ROOT / 'smtp.json')


def parse_link(link):
    legacy = LINK.fullmatch(link)
    if legacy:
        return legacy.groups()
    raw = RAW_LINK.fullmatch(link)
    if raw:
        return raw[1], raw[2], None, raw[3]
    fail('Supply the complete ezfileshare subscription link from the owner email.')


def email_owner(subscription, link, key, expiry, settings, bcc):
    message = EmailMessage()
    owner = subscription['owner']
    sender = settings.get('sender') or 'postmaster@' + subscription['domain']
    message['To'] = owner
    message['Date'] = format_datetime(datetime.now(timezone.utc))
    recipients = [owner]
    if bcc and bcc.lower() != owner.lower():
        recipients.append(bcc)
    sender_name = settings.get('sender_name', '')
    message['From'] = Address(display_name=sender_name, addr_spec=sender) if sender_name else sender
    domain = subscription['domain']
    message['Subject'] = 'Website removal and data export for ' + domain
    expires = datetime.fromtimestamp(expiry, timezone.utc).strftime('%Y-%m-%d %H:%M UTC')
    title = 'Your subscription archive is ready'
    intro = ('The Plesk subscription for ' + domain + ' is being removed. '
             'This removes the website and its subscription data from the hosting server. '
             'A complete export of the subscription is available to download.')
    privacy = 'Anyone with the download link can retrieve the archive. Keep the link private.'
    staging = 'To import it into Removal helper, paste the complete download link, including the fragment.'
    legacy = ('For older encrypted exports, decrypt the download with GnuPG using this password: ' + key +
              '. Use the same password if Plesk requests a backup password.') if key else ''
    plain = f'{title}\n\n{intro}\n\nDownload the subscription archive:\n{link}\n\nExpires {expires}.\n\n{privacy}\n\n{staging}\n'
    if legacy:
        plain += '\n' + legacy + '\n'
    message.set_content(plain)
    legacy_html = f'<p>{escape(legacy)}</p>' if legacy else ''
    message.add_alternative(
        f'''<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>{escape(title)}</title></head>
<body style="font-family:Arial,sans-serif;line-height:1.55;color:#17212b">
  <main style="max-width:620px;margin:0 auto;padding:24px">
    <h1 style="font-size:24px;margin:0 0 16px">{escape(title)}</h1>
    <p>{escape(intro)}</p>
    <p><a href="{escape(link, quote=True)}" style="color:#fff;background:#174683;padding:10px 16px;display:inline-block;text-decoration:none;border-radius:4px">Download the subscription archive</a></p>
    <p><strong>Expires {escape(expires)}.</strong></p>
    <p>{escape(privacy)}</p>
    <p>{escape(staging)}</p>
    {legacy_html}
  </main>
</body>
</html>''',
        subtype='html',
    )
    if not settings.get('host'):
        sendmail = ['/usr/sbin/sendmail', '-oi']
        sendmail += ['--', *recipients] if len(recipients) > 1 else ['-t']
        command(sendmail, secret=message.as_bytes(),
                message='The mail transport rejected the handoff. Subscription retained.')
        return
    context = ssl.create_default_context()
    relay = None
    try:
        if settings['tls'] == 'implicit':
            relay = smtplib.SMTP_SSL(settings['host'], settings['port'], timeout=30, context=context)
        else:
            relay = smtplib.SMTP(settings['host'], settings['port'], timeout=30)
            if settings['tls'] == 'starttls':
                relay.starttls(context=context)
        if settings['username']:
            relay.login(settings['username'], settings['password'])
        refused = relay.send_message(message, from_addr=sender, to_addrs=recipients)
        if refused:
            recipient = 'owner' if owner in refused else 'BCC'
            fail('The SMTP relay refused the ' + recipient + ' address. Subscription retained.')
    except smtplib.SMTPResponseException as error:
        fail('The SMTP relay rejected the handoff (SMTP %d). Subscription retained.' % error.smtp_code)
    except (OSError, smtplib.SMTPException):
        fail('Could not complete the handoff through the SMTP relay. Subscription retained.')
    finally:
        if relay:
            relay.close()


def receipt_link(receipt):
    if receipt.get('link'):
        return receipt['link']
    key = (Path(receipt['archive']).parent / 'archive-password').read_text().strip()
    return 'https://' + HOST + '/s/' + checked_id(receipt['share'], SHARE_ID) + '#plesk-v1.' + receipt['digest'] + '.' + key


def write_private_json(path, receipt):
    with tempfile.NamedTemporaryFile(mode='w', dir=ROOT, delete=False) as pending:
        json.dump(receipt, pending)
    Path(pending.name).replace(path)


def export(target, run=None, retry_of=None):
    if not GUID.fullmatch(target):
        fail('Invalid subscription identity.')
    with (ROOT / (target + '.lock')).open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        original = snapshot(target)
        settings = smtp_settings()
        bcc = sys.stdin.read(512).strip()
        if bcc and not MAILBOX.fullmatch(bcc):
            fail('The logged-in administrator email address is invalid.')
        routing = {key: value for key, value in settings.items() if key not in ('password', 'bcc_logged_in')}
        if bcc:
            routing['bcc'] = bcc
        receipt = ROOT / (target + '.handoff')
        previous = json.loads(receipt.read_text()) if receipt.exists() else None
        if (previous and retry_of and int(retry_of) in previous.get('runs', [])
                and not previous.get('removed') and previous['snapshot'] == original):
            resource = '/api/shares/' + previous['share'] + '/files/' + previous['file']
            current = request('GET', resource, stream=lambda r: copy_digest(r, previous['size']))
            if current != previous['digest'] or snapshot(target) != original:
                fail('The previously emailed handoff could not be reverified.')
            if (settings.get('host') or bcc) and previous.get('routing') != routing:
                link = receipt_link(previous)
                expiry = request('GET', '/api/shares/' + previous['share'])['expires_at']
                email_owner(original, link, parse_link(link)[2], expiry, settings, bcc)
                previous.update(link=link, routing=routing)
                if snapshot(target) != original:
                    fail('Subscription changed after email submission. Removal stopped.')
            previous['runs'].append(int(run))
            write_private_json(receipt, previous)
            return {'guid': target, 'archive': previous['archive']}
        work = Path(tempfile.mkdtemp(prefix='export-' + (run + '-' if run else ''), dir=ROOT))
        archive = work / ('subscription-' + target + '.tar')
        env = os.environ.copy()
        env.pop('PLESK_BACKUP_PASSWORD', None)
        suspended = original['status'] == 0
        handed_off = False
        try:
            if suspended:
                command([PLESK, 'bin', 'subscription', '--webspace-off', original['domain']])
            frozen = snapshot(target)
            if not frozen['status'] or {**original, 'status': frozen['status']} != frozen:
                fail('Subscription identity or contents changed before backup.')
            command([PLESK, 'bin', 'pleskbackup', '--domains-id', str(frozen['id']), '-output-file', str(archive)],
                    env=env,
                    message='Plesk did not complete the full subscription backup without errors.')
            command([PLESK, 'bin', 'pleskrestore', '--check-backup', str(archive)],
                    env=env)
            sid, fid, checksum, expiry, management_token = upload(archive)
            if snapshot(target) != frozen:
                fail('Subscription changed during transfer. Removal stopped.')
            link = 'https://' + HOST + '/s/' + sid + '#plesk-v2.' + checksum
            identity = json.dumps([target, frozen['domain'], frozen['owner']], ensure_ascii=False).encode()
            link += '.' + base64.urlsafe_b64encode(identity).decode().rstrip('=')
            email_owner(frozen, link, None, expiry, settings, bcc)
            if snapshot(target) != frozen:
                fail('Subscription changed after email submission. Removal stopped.')
            if previous:
                historical = ROOT / (checked_id(previous['share'], SHARE_ID) + '.handoff')
                if not historical.exists():
                    shutil.copy2(receipt, historical)
            write_private_json(receipt, {'snapshot': frozen, 'archive': str(archive), 'share': sid,
                                    'file': fid, 'digest': checksum, 'size': archive.stat().st_size,
                                    'link': link, 'management_token': management_token, 'routing': routing,
                                    'runs': [int(run)] if run else []})
            handed_off = True
            return {'guid': target, 'archive': str(archive)}
        finally:
            if suspended and not handed_off:
                current = snapshot(target)
                if current['domain'] == original['domain'] and current['status'] != 0:
                    command([PLESK, 'bin', 'subscription', '--webspace-on', current['domain']])


def stage(link, run=None):
    sid, expected, key, _ = parse_link(link)
    api = '/api/shares/' + sid
    files = request('GET', api)['files']
    suffix = '.tar.gpg' if key else '.tar'
    if len(files) != 1 or not files[0]['name'].startswith('subscription-') or not files[0]['name'].endswith(suffix):
        fail('This share does not contain a subscription export.')
    guid = files[0]['name'][len('subscription-'):-len(suffix)]
    if not GUID.fullmatch(guid):
        fail('Invalid subscription identity in archive filename.')
    subject, name, owner = import_identity(link)
    if GUID.fullmatch(subject) and subject.lower() != guid.lower():
        fail('The link identifies a different subscription than the archive.')
    if subject.startswith('share-'):
        for row in subscriptions():
            if row[1] == guid:
                name, owner = row[2:4]
                break
    size = files[0]['size']
    limits = request('GET', '/api/info')
    if type(size) is not int or not 0 < size <= min(limits['max_file_size'], limits['max_share_size']):
        fail('Invalid archive size.')
    work = Path(tempfile.mkdtemp(prefix='pending-' + (run + '-' if run else ''), dir=ROOT))
    try:
        archive = work / 'subscription.tar'
        download = archive.with_suffix('.tar.gpg') if key else archive
        with download.open('xb') as out:
            actual = request('GET', api + '/files/' + checked_id(files[0]['id'], FILE_ID),
                             stream=lambda r: copy_digest(r, size, out))
        if actual != expected:
            fail('Download checksum differs from the owner link.')
        if key:
            gpg(download, archive, key, work)
            download.unlink()
            (work / 'archive-password').write_text(key + '\n')
        (work / 'subscription.json').write_text(json.dumps({'guid': guid, 'name': name, 'owner': owner, 'share': sid, 'digest': actual}))
        # Atomically publish verified files inside a newly reserved private directory.
        destination = Path(tempfile.mkdtemp(prefix='import-' + (run + '-' if run else ''), dir=ROOT))
        work.rename(destination / 'archive')
        return str(destination / 'archive' / 'subscription.tar')
    finally:
        if work.exists():
            shutil.rmtree(work)


def import_identity(link):
    share, _, _, metadata = parse_link(link)
    if metadata:
        try:
            values = json.loads(base64.urlsafe_b64decode(metadata + '==='))
            guid, name, owner = values
            if (GUID.fullmatch(guid) and isinstance(name, str) and 0 < len(name) <= 255
                    and isinstance(owner, str) and len(owner) <= 320):
                return guid, name, owner
        except (TypeError, ValueError):
            pass
    for path in ROOT.glob('*.handoff'):
        receipt = json.loads(path.read_text())
        if receipt['share'] == share:
            snap = receipt['snapshot']
            return snap['guid'], snap['domain'], snap['owner']
    return 'share-' + share, 'Share ' + share, 'Unavailable'


def history_db():
    conn = sqlite3.connect(ROOT / 'history.sqlite', timeout=15)
    conn.row_factory = sqlite3.Row
    conn.execute('''CREATE TABLE IF NOT EXISTS runs (
        id INTEGER PRIMARY KEY, subject TEXT NOT NULL, name TEXT NOT NULL, owner TEXT NOT NULL,
        action TEXT NOT NULL, target TEXT NOT NULL, status TEXT NOT NULL, updated INTEGER NOT NULL,
        result TEXT NOT NULL, legacy TEXT UNIQUE)''')
    conn.execute('CREATE INDEX IF NOT EXISTS runs_subject ON runs(subject,id)')
    return conn


def queue(conn, action, target, retry=False):
    conn.execute('BEGIN IMMEDIATE')
    retry_of = None
    if retry:
        old = conn.execute('SELECT * FROM runs WHERE id=?', (target,)).fetchone()
        if not old or old['status'] != 'Failed':
            fail('Only a failed operation can be retried.')
        latest = conn.execute('SELECT id FROM runs WHERE subject=? ORDER BY id DESC LIMIT 1', (old['subject'],)).fetchone()
        if latest['id'] != old['id']:
            fail('A newer operation exists. Refresh the history.')
        action, target = old['action'], old['target']
        retry_of = old['id']
    if action == 'export':
        found = [r for r in subscriptions() if r[1] == target]
        if len(found) != 1:
            fail('This subscription is no longer available for removal.')
        _, subject, name, owner, _ = found[0]
    elif action == 'import':
        if not re.fullmatch('[a-f0-9]{32}', target):
            fail('Invalid import request.')
        subject, name, owner = import_identity((ROOT / ('request-' + target)).read_text())
    elif action == 'restore':
        staged = conn.execute('SELECT * FROM runs WHERE id=?', (target,)).fetchone()
        if staged_archive(staged) is None:
            fail('Select a staged import with an available archive.')
        subject, name, owner = staged['subject'], staged['name'], staged['owner']
    else:
        fail('Unknown transfer operation.')
    bcc = ''
    if action == 'export' and smtp_settings().get('bcc_logged_in'):
        bcc = sys.stdin.read(512).strip()
        if not MAILBOX.fullmatch(bcc):
            fail('Set a valid email address on your Plesk administrator profile or turn off BCC.')
    active = conn.execute("SELECT id FROM runs WHERE subject=? AND status IN ('Queued','Running')", (subject,)).fetchone()
    if active:
        fail('A transfer is already queued or running for this subscription.')
    cur = conn.execute('INSERT INTO runs(subject,name,owner,action,target,status,updated,result) VALUES(?,?,?,?,?,?,?,?)',
                       (subject, name, owner, action, target, 'Queued', int(time.time()), 'Waiting for Plesk.'))
    conn.commit()
    return dict(id=cur.lastrowid, action=action, target=target, retryOf=retry_of, bcc=bcc)


def legacy_history(conn, tasks):
    # Earlier releases kept handoff receipts, staging directories and worker locks.
    # A receipt proves email handoff; only a task result proves successful deletion.
    current = {row[1]: row for row in subscriptions()}
    def remember(key, subject, name, owner, action, target, status, timestamp, result):
        conn.execute('INSERT OR IGNORE INTO runs(subject,name,owner,action,target,status,updated,result,legacy) '
                     'VALUES(?,?,?,?,?,?,?,?,?)', (subject, name, owner, action, target, status, timestamp, result, key))
    for lock in ROOT.glob('*.lock'):
        guid = lock.stem
        if not GUID.fullmatch(guid) or conn.execute('SELECT 1 FROM runs WHERE subject=?', (guid,)).fetchone():
            continue
        receipt = ROOT / (guid + '.handoff')
        if receipt.exists():
            snap = json.loads(receipt.read_text())['snapshot']
            status = 'Handed off' if guid in current else 'No longer in Plesk'
            remember(guid, guid, snap['domain'], snap['owner'], 'export', guid, status,
                     int(receipt.stat().st_mtime), 'Owner emailed. Earlier version did not record the removal result.')
        else:
            row = current.get(guid)
            remember(guid, guid, row[2] if row else guid, row[3] if row else 'Unavailable',
                     'export', guid, 'Unknown', int(lock.stat().st_mtime), 'Earlier export attempt. Outcome unavailable.')
    for directory in ROOT.glob('import-*'):
        archive = directory / 'archive' / 'subscription.tar'
        if archive.is_file() and not conn.execute('SELECT 1 FROM runs WHERE result=? OR legacy=?',
                ('Verified archive staged at ' + str(archive), directory.name)).fetchone():
            # A staging worker may have just published its archive before recording success.
            if conn.execute("SELECT 1 FROM runs WHERE action='import' AND status='Running'").fetchone():
                continue
            remember(directory.name, directory.name, 'Staged archive ' + directory.name[7:], 'Unavailable',
                     'import', '', 'Staged', int(archive.stat().st_mtime), 'Verified archive staged at ' + str(archive))
    for task in tasks:
        if task.get('status') == 'done' and task.get('action') == 'export':
            guid = task.get('target') or ''
            if GUID.fullmatch(guid) and str(task.get('result', '')).startswith('Owner emailed and subscription removed.'):
                conn.execute("UPDATE runs SET status='Removed',result=? WHERE legacy=?",
                             (task['result'], guid))
            continue
        if task.get('status') != 'error' or not isinstance(task.get('target'), str):
            continue
        action, target = task['action'], task['target']
        if action == 'export' and GUID.fullmatch(target):
            row = current.get(target)
            if not row:
                continue
            subject, name, owner = target, row[2], row[3]
            evidence = ROOT / (target + '.lock')
        elif action == 'import' and re.fullmatch('[a-f0-9]{32}', target):
            evidence = ROOT / ('request-' + target)
            if not evidence.is_file():
                continue
            subject, name, owner = import_identity(evidence.read_text())
        else:
            continue
        if conn.execute('SELECT 1 FROM runs WHERE subject=? AND legacy IS NULL', (subject,)).fetchone():
            continue
        if action == 'export' and conn.execute("SELECT 1 FROM runs WHERE subject=? AND status='Removed'", (subject,)).fetchone():
            continue
        remember('task-' + str(task['id']), subject, name, owner, action, target, 'Failed',
                 int(evidence.stat().st_mtime) if evidence.exists() else 0, 'Earlier Plesk task reported failure.')
    conn.commit()


def removal_receipts():
    receipts = {}
    for path in ROOT.glob('*.handoff'):
        receipt = json.loads(path.read_text())
        receipts.setdefault(receipt['snapshot']['guid'], []).append((path, receipt))
    return receipts


def removal_receipt(row, receipts):
    if row['action'] != 'export':
        return None
    older = []
    for path, receipt in receipts.get(row['target'], []):
        if row['id'] in receipt.get('runs', []) or receipt['archive'] in row['result']:
            return path
        if not receipt.get('runs') and row['status'] in ('Removed', 'No longer in Plesk', 'Handed off'):
            timestamp = int(path.stat().st_mtime)
            if timestamp <= row['updated']:
                older.append((timestamp, path))
    return max(older)[1] if older else None


def recoveries(row, receipt):
    roots = set()
    for prefix in ('export', 'import', 'pending'):
        roots.update(ROOT.glob('%s-%d-*' % (prefix, row['id'])))
    if receipt:
        roots.add(Path(json.loads(receipt.read_text())['archive']).parent)
    if row['action'] == 'import':
        match = re.fullmatch(r'Verified archive staged at (.+)/archive/subscription.tar', row['result'])
        if match:
            roots.add(Path(match[1]))
    return sorted(path for path in roots if path.parent == ROOT and path.is_dir() and not path.is_symlink()
                  and re.fullmatch(r'(?:export|import|pending)-(?:[1-9][0-9]*-)?[a-z0-9_]{8}', path.name))


def finish_removal(target):
    receipt = ROOT / (target + '.handoff')
    handoff = json.loads(receipt.read_text())
    directory = Path(handoff['archive']).parent
    if directory.parent != ROOT or not re.fullmatch(r'export-(?:[1-9][0-9]*-)?[a-z0-9_]{8}', directory.name):
        fail('Invalid local recovery directory.')
    if directory.is_symlink():
        fail('Invalid local recovery directory.')
    if not handoff.get('link') and directory.exists():
        handoff['link'] = receipt_link(handoff)
    handoff['removed'] = True
    write_private_json(receipt, handoff)
    if directory.exists():
        shutil.rmtree(directory)


def cleanup(conn, run):
    conn.execute('BEGIN IMMEDIATE')
    row = conn.execute('SELECT * FROM runs WHERE id=?', (run,)).fetchone()
    if not row or row['status'] in ('Queued', 'Running'):
        fail('Recovery files can only be cleaned up after a job finishes.')
    active = conn.execute("SELECT 1 FROM runs WHERE subject=? AND status IN ('Queued','Running')", (row['subject'],)).fetchone()
    if active:
        fail('Wait for the current subscription transfer to finish.')
    receipt = removal_receipt(row, removal_receipts())
    paths = recoveries(row, receipt)
    if not paths:
        fail('No recovery files remain for this job.')
    if receipt:
        handoff = json.loads(receipt.read_text())
        if not handoff.get('link') and Path(handoff['archive']).parent in paths:
            handoff['link'] = receipt_link(handoff)
            write_private_json(receipt, handoff)
    for path in paths:
        shutil.rmtree(path)
    conn.execute("UPDATE runs SET result=result || ' Local recovery files deleted.' WHERE id=?", (run,))


def staged_archive(row):
    if not row or row['action'] != 'import' or row['status'] != 'Staged':
        return None
    match = re.fullmatch(r'Verified archive staged at (.+)/archive/subscription.tar', row['result'])
    if not match:
        return None
    directory = Path(match[1])
    if directory.parent != ROOT or not re.fullmatch(r'import-(?:[1-9][0-9]*-)?[a-z0-9_]{8}', directory.name):
        return None
    archive = directory / 'archive' / 'subscription.tar'
    keyfile = archive.with_name('archive-password')
    if archive.is_file() and archive.resolve() == archive and (not keyfile.exists() or keyfile.resolve() == keyfile):
        return archive
    return None


def restore_preflight(inventory):
    names = {inventory['domain'].lower()}
    names.update(row[1].lower() for row in inventory['sites'] + inventory['aliases'])
    databases = {row[1].lower() for row in inventory['databases']}
    for name in names:
        if not re.fullmatch(r'[a-z0-9_][a-z0-9_.-]*', name) or '..' in name or name.endswith('.'):
            fail('Restore blocked: the export contains an invalid domain name.')
    conflicts = set()
    for guid, name in db('domain inventory', 'SELECT guid,name FROM domains'):
        if guid == inventory['guid'] or name.lower() in names:
            conflicts.add('domain ' + name)
    for (name,) in db('domain aliases', 'SELECT name FROM domain_aliases'):
        if name.lower() in names:
            conflicts.add('alias ' + name)
    for (name,) in db('DNS zones', 'SELECT name FROM dns_zone'):
        if name.lower().rstrip('.') in names:
            conflicts.add('DNS zone ' + name)
    if databases:
        existing = db('database inventory', 'SELECT name FROM data_bases '
                      'UNION SELECT schema_name FROM information_schema.schemata')
        conflicts.update('database ' + name for (name,) in existing if name.lower() in databases)

    # Mailboxes managed by Plesk belong to a domain. Check leftover vhost and
    # mailbox directories too, even if the associated domain was removed from Plesk.
    config = Path('/etc/psa/psa.conf').read_text()
    for setting, fallback in (('HTTPD_VHOSTS_D', '/var/www/vhosts'),
                              ('QMAIL_MAILNAMES_D', '/var/qmail/mailnames')):
        match = re.search(r'^' + setting + r'\s+([^\s#]+)', config, re.MULTILINE)
        parent = Path(match[1].strip('"\'') if match else fallback)
        if not parent.is_absolute():
            fail('Restore blocked: could not locate Plesk data directories.')
        for name in names:
            candidate = parent / name
            if os.path.lexists(candidate):
                conflicts.add('path ' + str(candidate))
    if conflicts:
        fail('Restore blocked by existing resources: ' + ', '.join(sorted(conflicts)[:20]) + '.')


def restore(run):
    with history_db() as conn:
        row = conn.execute('SELECT * FROM runs WHERE id=?', (run,)).fetchone()
        archive = staged_archive(row)
    if archive is None:
        fail('The staged archive is no longer available.')
    keyfile = archive.with_name('archive-password')
    password = keyfile.read_text().strip() if keyfile.is_file() else None
    if password is not None and not re.fullmatch('[a-f0-9]{64}', password):
        fail('The staged archive password is invalid.')
    identity_file = archive.with_name('subscription.json')
    identity = json.loads(identity_file.read_text()) if identity_file.is_file() else {}
    inventory = None
    for path in ROOT.glob('*.handoff'):
        receipt = json.loads(path.read_text())
        try:
            _, _, receipt_password, _ = parse_link(receipt_link(receipt))
        except FileNotFoundError:
            continue
        if (receipt_password is None) != (password is None):
            continue
        if password and not secrets.compare_digest(receipt_password, password):
            continue
        if identity.get('share') == receipt['share'] and identity.get('digest') == receipt['digest']:
            inventory = receipt['snapshot']
            break
        if password and not identity.get('digest'):
            # Old staging runs did not record the downloaded ciphertext digest.
            # Compare their archive to the copy retained by the original export.
            original = Path(receipt['archive'])
            if not original.is_file():
                continue
            with tempfile.TemporaryDirectory(dir=ROOT) as directory:
                work = Path(directory)
                decrypted = work / 'subscription.tar'
                gpg(original, decrypted, password, work)
                size = archive.stat().st_size
                if decrypted.stat().st_size == size:
                    with decrypted.open('rb') as source, archive.open('rb') as staged:
                        if copy_digest(source, size) == copy_digest(staged, size):
                            inventory = receipt['snapshot']
                            break
    if inventory is None:
        fail('Restore blocked: no matching export inventory was found on this server.')

    env = os.environ.copy()
    env.pop('PLESK_BACKUP_PASSWORD', None)
    if password:
        env['PLESK_BACKUP_PASSWORD'] = password
    with (ROOT / 'restore.lock').open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        command([PLESK, 'bin', 'pleskrestore', '--check-backup', str(archive)], env=env,
                message='Plesk could not verify the staged backup.')
        restore_preflight(inventory)
        result = command([PLESK, 'bin', 'pleskrestore', '--restore', str(archive), '-level', 'domains', '-verbose'],
                         env=env, capture=True,
                         message='Plesk reported a restore failure. Review the Plesk restore log before retrying.')
        if not any(row[2] == inventory['domain'] for row in subscriptions()):
            fail('Plesk did not recreate the subscription. Review the Plesk restore log.')
        if re.search(rb'\b(?:warnings?|errors?)\b', result, re.IGNORECASE):
            return 'Subscription restored with diagnostics. Review the Plesk restore log and subscription status.'
    return 'Subscription restored. Check its activation status in Plesk.'


def history(conn, tasks):
    legacy_history(conn, tasks)
    rows = conn.execute('SELECT * FROM runs '
                        'ORDER BY id DESC')
    receipts = removal_receipts()
    seen = set()
    for raw in rows:
        row = dict(raw)
        row['latest'] = row['subject'] not in seen
        seen.add(row['subject'])
        path = removal_receipt(row, receipts)
        if row['action'] == 'export' and row['status'] in ('Removed', 'No longer in Plesk'):
            if path:
                receipt = json.loads(path.read_text())
                share = checked_id(receipt['share'], SHARE_ID)
                row['link'] = receipt.get('link')
                if not row['link']:
                    keyfile = Path(receipt['archive']).parent / 'archive-password'
                    if keyfile.exists():
                        row['link'] = 'https://' + HOST + '/s/' + share + '#plesk-v1.' + receipt['digest'] + '.' + keyfile.read_text().strip()
                if receipt.get('management_token'):
                    row['manage'] = 'https://' + HOST + '/m/' + share + '#' + receipt['management_token']
        row['can_cleanup'] = row['status'] not in ('Queued', 'Running') and bool(recoveries(row, path))
        row['can_restore'] = staged_archive(row) is not None
        if row['latest'] or row['can_cleanup'] or row.get('link'):
            yield row


def history_command(action, args):
    with history_db() as conn:
        if action == 'history' and not args:
            print(json.dumps(list(history(conn, json.load(sys.stdin)))))
        elif action == 'queue' and len(args) == 2:
            print(json.dumps(queue(conn, *args)))
        elif action == 'retry' and len(args) == 1:
            print(json.dumps(queue(conn, None, args[0], retry=True)))
        elif action == 'cleanup' and len(args) == 1:
            cleanup(conn, args[0])
        elif action == 'record' and len(args) == 2:
            run, state = args
            transitions = {'Running': ('Queued',), 'Failed': ('Queued', 'Running'),
                           'Removed': ('Running',), 'Staged': ('Running',), 'Restored': ('Running',)}
            if state not in transitions:
                fail('Invalid transfer state.')
            allowed = transitions[state]
            placeholders = ','.join('?' for _ in allowed)
            updated = conn.execute('UPDATE runs SET status=?,updated=?,result=? WHERE id=? AND status IN (' +
                                   placeholders + ')', (state, int(time.time()), sys.stdin.read(4096), run, *allowed))
            if updated.rowcount != 1:
                fail('This transfer is no longer in the expected state.')
        else:
            fail('Unknown history operation.')


def published_release(installed=None):
    # Read the version from the exact published package Plesk would install.
    # The Plesk installer can delegate extraction to its panel user.
    # Keep public package bytes outside the root-only recovery directory.
    with tempfile.TemporaryDirectory(prefix='ezfileshare-release-', dir='/tmp') as directory:
        package = Path(directory) / 'ezfileshare.zip'
        conn = http.client.HTTPSConnection(HOST, timeout=5)
        try:
            conn.request('GET', '/extensions/ezfileshare-plesk.zip')
            response = conn.getresponse()
            if response.status != 200:
                fail('Could not retrieve the published extension package (HTTP %d).' % response.status)
            with package.open('xb') as output:
                for chunk in iter(lambda: response.read(BLOCK), b''):
                    if output.tell() + len(chunk) > 16 * BLOCK:
                        fail('Published extension package exceeds the download limit.')
                    output.write(chunk)
        finally:
            conn.close()
        with zipfile.ZipFile(package) as archive:
            metadata = archive.getinfo('meta.xml')
            if metadata.file_size > 65536:
                fail('Invalid extension metadata.')
            module = ElementTree.fromstring(archive.read(metadata))
        version = (module.findtext('version') or '').strip()
        pattern = r'[0-9]+\.[0-9]+\.[0-9]+'
        if module.findtext('id') != 'ezfileshare' or not re.fullmatch(pattern, version):
            fail('Invalid published extension identity or version.')
        if installed is not None:
            if not re.fullmatch(pattern, installed):
                fail('Unknown installed extension version.')
            if tuple(map(int, version.split('.'))) <= tuple(map(int, installed.split('.'))):
                fail('No newer version is available.')
            package.chmod(0o644)
            Path(directory).chmod(0o755)
            # The installer inherits the caller's umask. Plesk's panel must be
            # able to traverse and read the installed extension.
            private_umask = os.umask(0o022)
            try:
                command([PLESK, 'bin', 'extension', '--upgrade', str(package)],
                        message='Plesk could not upgrade the extension. Check the Plesk panel log for details.')
            finally:
                os.umask(private_umask)
            admin = Path(__file__).absolute().parents[2]
            index = admin / 'htdocs/modules/ezfileshare/index.php'
            metadata = admin / 'plib/modules/ezfileshare/meta.xml'
            if not index.is_file() or not metadata.is_file() or ElementTree.parse(metadata).findtext('version') != version:
                fail('Plesk did not install the new extension files. Upload the release ZIP in My Extensions.')
        return version


def main():
    os.umask(0o077)
    ROOT.mkdir(mode=0o700, exist_ok=True)
    st = ROOT.lstat()
    if not ROOT.is_dir() or ROOT.is_symlink() or st.st_uid != 0 or st.st_mode & 0o077:
        fail('Transfer storage must be a private root-owned directory.')
    action, *args = sys.argv[1:]
    if action in ('import', 'export') and len(args) == 2 and not re.fullmatch('[1-9][0-9]*', args[1]):
        fail('Invalid transfer run ID.')
    if action in ('history', 'queue', 'retry', 'record', 'cleanup'):
        history_command(action, args)
    elif action == 'latest-version' and not args:
        print(published_release())
    elif action == 'upgrade' and len(args) == 1:
        published_release(args[0])
    elif action == 'restore' and len(args) == 2 and all(re.fullmatch('[1-9][0-9]*', arg) for arg in args):
        print(restore(args[0]))
    elif action == 'list' and not args:
        print(json.dumps([{'id': int(ident), 'target': guid, 'label': name + ' — ' + owner}
                          for ident, guid, name, owner, _ in subscriptions()]))
    elif action == 'smtp-settings' and not args:
        settings = smtp_settings()
        settings['has_password'] = bool(settings.pop('password', ''))
        print(json.dumps(settings))
    elif action == 'save-smtp' and not args:
        save_smtp()
    elif action == 'finish-removal' and len(args) == 1 and GUID.fullmatch(args[0]):
        finish_removal(args[0])
    elif action == 'export' and 1 <= len(args) <= 3 and all(re.fullmatch('[1-9][0-9]*', arg) for arg in args[1:]):
        print(json.dumps(export(*args)))
    elif action == 'queue-import' and not args:
        link = sys.stdin.read(4096).strip()
        parse_link(link)
        ticket = secrets.token_hex(16)
        with (ROOT / ('request-' + ticket)).open('x') as out:
            out.write(link)
        print(ticket)
    elif action == 'import' and len(args) in (1, 2) and re.fullmatch('[a-f0-9]{32}', args[0]):
        ticket = ROOT / ('request-' + args[0])
        archive = stage(ticket.read_text(), args[1] if len(args) == 2 else None)
        identity = json.loads((Path(archive).parent / 'subscription.json').read_text())
        with history_db() as conn:
            conn.execute("UPDATE runs SET subject=?,name=?,owner=? WHERE target=? AND status='Running' AND action='import'",
                         (identity['guid'], identity['name'], identity['owner'], args[0]))
        ticket.unlink()
        print('Verified archive staged at ' + archive)
    else:
        fail('Unknown transfer operation.')


if __name__ == '__main__':
    try:
        main()
    except (ValueError, KeyError, OSError, http.client.HTTPException, zipfile.BadZipFile, ElementTree.ParseError) as error:
        sys.exit(str(error))
