"""Bounded AI2 transport; credentials stay in stdin, never in logs or archives."""
import os
from pathlib import Path
import shlex
import stat
import subprocess

ROOT = Path(__file__).resolve().parent
SSH = ['ssh', '-T', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=6',
       '-o', 'StrictHostKeyChecking=yes', '-o',
       'UserKnownHostsFile=/root/.ssh/contextra_icerti2_known_hosts',
       '-i', '/root/.ssh/ltb1021_contextra_icerti2_si_ed25519',
       '-p', '1022', 'si@58.233.207.31']
PASSWORD = Path('/data/contextra-icerti2-sudo.lwK98t/password')


def run(code, *, root=False, timeout=30):
    command = 'python3 -c ' + shlex.quote(code)
    data = None
    if root:
        for p, mode in ((PASSWORD.parent, 0o700), (PASSWORD, 0o600)):
            s = p.lstat()
            if stat.S_ISLNK(s.st_mode) or s.st_uid != 0 or stat.S_IMODE(s.st_mode) != mode:
                raise RuntimeError('Private sudo file ownership/mode mismatch')
        data = PASSWORD.read_bytes()
        if not data or len(data) > 4096 or b'\0' in data or b'\n' in data.rstrip(b'\n'):
            raise RuntimeError('Invalid password file framing')
        command = 'sudo -S -p "" ' + command
    p = subprocess.run([*SSH, command], input=data, capture_output=True, timeout=timeout)
    if p.returncode:
        raise RuntimeError('Remote command failed (%s): %s' %
                           (p.returncode, p.stderr.decode(errors='replace')[-1800:]))
    return p.stdout


def save(name, data):
    p = ROOT/name
    with p.open('xb') as f:
        os.fchmod(f.fileno(), 0o600)
        f.write(data)
