#!/bin/sh
# A new installation requires a single-use invite token from Seinari.
# Keep the program separate from stdin: sudo can then ask through the terminal.
# Parse the complete body before any blocking command; live edits cannot change this run.
main() {
set -eu
if [ "$(uname -s)" = Darwin ]; then
    mac_installer=$(mktemp "${TMPDIR:-/tmp}/seinari-connect-macos.XXXXXXXX")
    chmod 700 "$mac_installer"
    trap 'rm -f "$mac_installer"' EXIT HUP INT TERM
    curl -fsSL --proto '=https' https://seinari.ai/connect-api/install/macos -o "$mac_installer"
    /bin/sh "$mac_installer" "$@"
    exit $?
fi
installer=$(mktemp "${TMPDIR:-/tmp}/seinari-connect.XXXXXXXX")
chmod 700 "$installer"
cat > "$installer" <<'ROOT_SCRIPT'
#!/bin/sh
# Parse the complete body before any blocking command; live edits cannot change this run.
main() {
set -eu
umask 077
source_file=$0
state=/var/lib/seinari-connect
bin=/usr/local/bin/seinari-connect
owned=0
user_created=0
complete=0
policy_owned=0
policy_backup=
fail() { printf 'seinari_connect_error: %s\n' "$*" >&2; exit 1; }
cleanup() {
    result=$?
    trap - EXIT HUP INT TERM
    if [ "$policy_owned" = 1 ]; then
        rm -f /usr/sbin/policy-rc.d
        if [ -n "$policy_backup" ]; then
            mv "$policy_backup/policy-rc.d" /usr/sbin/policy-rc.d
            rmdir "$policy_backup"
        fi
    fi
    if [ "$owned" = 1 ] && [ "$complete" != 1 ]; then
        if [ -x "$bin" ]; then "$bin" stop --rollback || true; fi
        if [ "$user_created" = 1 ] && [ "$(id -u seinari 2>/dev/null || true)" = "$created_uid" ]; then
            userdel -r seinari >/dev/null 2>&1 || true
        fi
        rm -f /etc/sudoers.d/seinari-connect "$bin"
        rm -rf "$state"
    fi
    rm -f "$source_file"
    exit "$result"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' HUP TERM
[ "$(id -u)" = 0 ] || fail 'root_required: please run with sudo.'
[ "$(uname -s)" = Linux ] || fail 'unsupported_os: this installer requires Linux.'
if [ -e "$state" ] || [ -L "$state" ]; then
    if [ -f "$state/managed" ] && [ "$(cat "$state/managed")" = seinari-connect-v1 ] && [ -x "$bin" ]; then
        if "$bin" status; then
            printf '\nAlready installed. Disconnect with: sudo seinari-connect stop\n'
            exit 0
        fi
        printf 'Cleaning up an interrupted Seinari Connect installation.\n'
        "$bin" stop --rollback
    else
        fail "state_exists: refusing to overwrite $state."
    fi
fi
id seinari >/dev/null 2>&1 && fail 'user_exists: refusing to change the existing seinari account.'
for path in /home/seinari "$bin" /etc/sudoers.d/seinari-connect /etc/systemd/system/seinari-connect-sshd.service /etc/systemd/system/seinari-connect-tunnel.service /etc/systemd/system/seinari-connect-heartbeat.service /etc/systemd/system/seinari-connect-heartbeat.timer; do
    [ ! -e "$path" ] && [ ! -L "$path" ] || fail "path_exists: refusing to overwrite $path."
done
[ -r /dev/tty ] && [ -w /dev/tty ] || fail 'invite_required: run in a terminal with your Seinari Connect invite token.'
invite_token=$(
    tty_mode=$(stty -g </dev/tty) || exit 1
    trap 'stty "$tty_mode" </dev/tty; printf "\n" >/dev/tty' EXIT
    trap 'exit 1' HUP INT TERM
    printf 'Seinari Connect invite token: ' >/dev/tty
    stty -echo </dev/tty || exit 1
    IFS= read -r token </dev/tty || exit 1
    printf '%s' "$token"
) || fail 'invite_required: enter the token in an interactive terminal.'
case "$invite_token" in ''|*[!A-Za-z0-9_-]*) fail 'invite_required: enter the token issued by Seinari.' ;; esac
[ "${#invite_token}" -eq 43 ] || fail 'invite_required: enter the token issued by Seinari.'
# Keep distro packages installed on disconnect. Never enable the distro sshd.
had_sshd=0
command -v sshd >/dev/null 2>&1 && had_sshd=1
missing=0
for cmd in python3 ssh ssh-keygen sshd autossh sudo useradd userdel visudo; do
    command -v "$cmd" >/dev/null 2>&1 || missing=1
done
if [ "$missing" = 1 ]; then
    if command -v apt-get >/dev/null 2>&1; then
        # Debian package hooks must not start or restart the host's SSH service.
        policy=/usr/sbin/policy-rc.d
        if [ -e "$policy" ] || [ -L "$policy" ]; then
            policy_backup=$(mktemp -d /usr/sbin/seinari-policy.XXXXXXXX)
            mv "$policy" "$policy_backup/policy-rc.d"
        fi
        policy_owned=1
        printf '#!/bin/sh\nexit 101\n' > "$policy"
        chmod 755 "$policy"
        apt-get update -qq
        DEBIAN_FRONTEND=noninteractive apt-get install -y -qq python3 openssh-server openssh-client autossh sudo
        rm -f "$policy"
        if [ -n "$policy_backup" ]; then
            mv "$policy_backup/policy-rc.d" "$policy"
            rmdir "$policy_backup"
        fi
        policy_owned=0
    elif command -v dnf >/dev/null 2>&1; then
        dnf install -y python3 openssh-server openssh-clients autossh sudo
    elif command -v yum >/dev/null 2>&1; then
        yum install -y python3 openssh-server openssh-clients autossh sudo
    elif command -v zypper >/dev/null 2>&1; then
        zypper --non-interactive install python3 openssh autossh sudo
    elif command -v pacman >/dev/null 2>&1; then
        pacman -S --noconfirm --needed python openssh autossh sudo
    else
        fail 'unsupported_package_manager: install python3, OpenSSH client/server, autossh and sudo, then rerun.'
    fi
fi
# Package presets may enable the distro daemon even when policy-rc.d denies start.
# Only disable a newly installed server; preserve every existing SSH installation.
if [ "$had_sshd" = 0 ] && [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1; then
    systemctl disable --now ssh.service ssh.socket sshd.service sshd.socket >/dev/null 2>&1 || true
fi
for cmd in python3 ssh ssh-keygen sshd autossh sudo useradd userdel visudo; do
    command -v "$cmd" >/dev/null 2>&1 || fail "missing_dependency: $cmd."
done
python3 - <<'PORT_CHECK'
import sys
if sys.version_info < (3, 8):
    raise SystemExit('seinari_connect_error: unsupported_python: Python 3.8 or later is required.')
import socket
try:
    with socket.socket() as s:
        s.bind(('127.0.0.1', 22228))
except OSError:
    raise SystemExit('seinari_connect_error: port_in_use: localhost:22228 is already occupied.')
PORT_CHECK
mkdir -m 700 "$state"
printf 'seinari-connect-v1\n' > "$state/managed"
owned=1
mkdir -p /usr/local/bin /etc/sudoers.d
bin_tmp=$(mktemp "${bin}.XXXXXXXX")
cat > "$bin_tmp" <<'PYTHON'
#!/usr/bin/env python3
"""The root-owned lifecycle of one explicitly enrolled machine."""
import base64
import json
import os
from pathlib import Path
import pwd
import re
import shutil
import signal
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.request

STATE = Path('/var/lib/seinari-connect')
SELF = '/usr/local/bin/seinari-connect'
API = 'https://seinari.ai/connect-api'
UNITS = ['seinari-connect-heartbeat.timer', 'seinari-connect-heartbeat.service',
         'seinari-connect-tunnel.service', 'seinari-connect-sshd.service']


def error(text):
    raise RuntimeError(text)


def load():
    if STATE.is_symlink() or (STATE / 'managed').read_text().strip() != 'seinari-connect-v1':
        error('unmanaged_state: refusing to change this installation')
    p = STATE / 'record.json'
    return json.loads(p.read_text()) if p.exists() else {}


def save(record):
    p = STATE / 'record.tmp'
    p.write_text(json.dumps(record))
    p.chmod(0o600)
    p.replace(STATE / 'record.json')


def metadata():
    def run(args):
        try:
            return subprocess.check_output(args, stderr=subprocess.DEVNULL, timeout=6).decode(errors='replace').strip()
        except (OSError, subprocess.SubprocessError):
            return ''
    gpu = run(['nvidia-smi', '--query-gpu=name', '--format=csv,noheader'])
    driver = run(['nvidia-smi', '--query-gpu=driver_version', '--format=csv,noheader'])
    if not gpu:
        amd_smi = shutil.which('amd-smi') or '/opt/rocm/bin/amd-smi'
        asic = run([amd_smi, 'static', '--asic', '--json'])
        if asic:
            try:
                devices = json.loads(asic).get('gpu_data', [])
                gpu = '\n'.join(' '.join(str(v) for v in (a.get('market_name'), a.get('target_graphics_version')) if v and v != 'N/A')
                                for a in (device.get('asic', {}) for device in devices)).strip()
            except (AttributeError, TypeError, ValueError):
                pass
        if gpu:
            driver = run([amd_smi, 'version'])
    if not gpu:
        gpu = run(['rocm-smi', '--showproductname', '--json'])
        if gpu:
            driver = run(['rocm-smi', '--showdriverversion', '--json'])
    if not gpu:
        gpu = '\n'.join(line for line in run(['lspci', '-mm', '-nn']).splitlines()
                        if re.match(r'^\S+ "[^"]*\[03[0-9a-fA-F]{2}\]"', line))
    os_name = ''
    try:
        for line in Path('/etc/os-release').read_text().splitlines():
            if line.startswith('PRETTY_NAME='):
                os_name = line.split('=', 1)[1].strip('"\'')
    except OSError:
        pass
    return {'gpu': gpu[:900] or 'No GPU detected', 'driver': driver[:900] or 'Not detected',
            'os': (os_name or 'Linux')[:900]}


def post(endpoint, body, token=None):
    data = json.dumps(body, ensure_ascii=False).encode()
    if len(data) > 4096:
        error('metadata_too_large: request exceeds 4 KiB')
    headers = {'Content-Type': 'application/json', 'User-Agent': 'seinari-connect/1'}
    if token:
        headers['Authorization'] = 'Bearer ' + token
    req = urllib.request.Request(API + '/' + endpoint, data=data, headers=headers, method='POST')
    # Never follow redirects carrying the authorization token or enrollment data.
    class NoRedirect(urllib.request.HTTPRedirectHandler):
        def redirect_request(self, *args, **kwargs):
            return None
    try:
        with urllib.request.build_opener(NoRedirect()).open(req, timeout=12) as r:
            result = r.read(4097)
        if len(result) > 4096:
            error('response_too_large: API response exceeds 4 KiB')
        return json.loads(result) if result else {}
    except urllib.error.HTTPError as e:
        if endpoint == 'enroll' and e.code == 403:
            error('invite_required: enter a fresh token issued by Seinari')
        error('api_http_error: ' + str(e.code))
    except urllib.error.URLError:
        error('api_unreachable: check the Internet connection')


def public_key(text):
    parts = text.split()
    if len(parts) < 2 or parts[0] != 'ssh-ed25519' or '\n' in text.strip():
        error('invalid_api_key: expected an Ed25519 public key')
    try:
        raw = base64.b64decode(parts[1], validate=True)
    except ValueError:
        error('invalid_api_key: invalid base64')
    if len(raw) != 51 or raw[:19] != b'\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20':
        error('invalid_api_key: invalid Ed25519 key')
    return ' '.join(parts[:2])


def enroll():
    record = load()
    body = metadata()
    body.update(tunnel_key=(STATE / 'tunnel.pub').read_text().strip(),
                host_key=(STATE / 'host.pub').read_text().strip())
    response = post('enroll', body, sys.stdin.readline().strip())
    # Preserve the remote revocation capability even if another response field is bad.
    if isinstance(response, dict) and isinstance(response.get('code'), str) and isinstance(response.get('token'), str):
        record.update(code=response['code'], token=response['token'])
        save(record)
    if not isinstance(response, dict):
        error('invalid_enrollment: expected a JSON object')
    code, token = response.get('code'), response.get('token')
    if not isinstance(code, str) or not re.fullmatch(r'[A-Za-z0-9_-]{3,80}', code):
        error('invalid_enrollment: invalid code')
    if not isinstance(token, str) or not re.fullmatch(r'[A-Za-z0-9._~-]{16,1024}', token):
        error('invalid_enrollment: invalid token')
    host = response.get('edge_host')
    if not isinstance(host, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9.:-]{0,252}', host):
        error('invalid_enrollment: invalid edge hostname')
    for field in ['port', 'edge_port']:
        if type(response.get(field)) is not int or not 1 <= response[field] <= 65535:
            error('invalid_enrollment: invalid ' + field)
    user = response.get('edge_user')
    if not isinstance(user, str) or not re.fullmatch(r'seinari-tunnel-[A-Za-z0-9_-]{3,80}', user):
        error('invalid_enrollment: invalid edge username')
    known = response.get('edge_host_key', '').strip().split()
    if len(known) < 3:
        error('invalid_enrollment: missing edge host key')
    # Pin the returned public key with our own stable host label, regardless of DNS/port.
    key = public_key(' '.join(known[1:]))
    (STATE / 'known_hosts').write_text('seinari-connect-edge ' + key + '\n')
    (STATE / 'authorized_keys').write_text(public_key(response.get('admin_key', '')) + '\n')
    record.update({k: response[k] for k in ['code', 'token', 'port', 'edge_host', 'edge_port', 'edge_user']})
    save(record)


def sshd_command():
    return [shutil.which('sshd') or '/usr/sbin/sshd', '-D', '-e', '-f', str(STATE / 'sshd_config')]


def tunnel_command(record):
    return [shutil.which('autossh') or '/usr/bin/autossh', '-M', '0', '-N', '-T',
            '-i', str(STATE / 'tunnel'), '-p', str(record['edge_port']),
            '-o', 'BatchMode=yes', '-o', 'IdentitiesOnly=yes', '-o', 'IdentityAgent=none',
            '-o', 'ExitOnForwardFailure=yes', '-o', 'ServerAliveInterval=15',
            '-o', 'ServerAliveCountMax=3', '-o', 'StrictHostKeyChecking=yes',
            '-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'HostKeyAlias=seinari-connect-edge',
            '-o', 'UserKnownHostsFile=' + str(STATE / 'known_hosts'),
            '-o', 'ConnectTimeout=10', '-o', 'PasswordAuthentication=no',
            '-R', '127.0.0.1:%s:127.0.0.1:22228' % record['port'],
            record['edge_user'] + '@' + record['edge_host']]


def heartbeat():
    record = load()
    return post('heartbeat', dict(code=record['code'], **metadata()), record['token'])


def process_identity(pid):
    try:
        text = Path('/proc/%s/stat' % pid).read_text()
        start = text[text.rfind(')') + 2:].split()[19]
        args = Path('/proc/%s/cmdline' % pid).read_bytes().split(b'\0')
        return start, args
    except (OSError, IndexError):
        return None, []


def supervise():
    children = {}
    stopping = False
    def stop(signum, frame):
        nonlocal stopping
        stopping = True
        for child in children.values():
            if child.poll() is None:
                child.terminate()
    signal.signal(signal.SIGTERM, stop)
    signal.signal(signal.SIGINT, stop)
    last_heartbeat = 0
    while not stopping:
        for name, cmd in [('sshd', sshd_command()), ('tunnel', tunnel_command(load()))]:
            if name not in children or children[name].poll() is not None:
                children[name] = subprocess.Popen(cmd, env=dict(os.environ, AUTOSSH_GATETIME='0'))
        if time.monotonic() - last_heartbeat >= 60:
            last_heartbeat = time.monotonic()
            try:
                heartbeat()
            except Exception as e:
                print('Heartbeat: ' + str(e), file=sys.stderr, flush=True)
        time.sleep(1)
    for child in children.values():
        try:
            child.wait(timeout=5)
        except subprocess.TimeoutExpired:
            child.kill()
            child.wait()


def start():
    record = load()
    if record['mode'] == 'systemd':
        subprocess.run(['systemctl', 'daemon-reload'], check=True)
        subprocess.run(['systemctl', 'enable', '--now', UNITS[3], UNITS[2], UNITS[0]], check=True)
        time.sleep(1)
        subprocess.run(['systemctl', 'is-active', '--quiet', UNITS[3], UNITS[2]], check=True)
    else:
        with open(STATE / 'service.log', 'ab', buffering=0) as log:
            child = subprocess.Popen([SELF, 'supervise'], stdin=subprocess.DEVNULL, stdout=log,
                                     stderr=log, start_new_session=True, close_fds=True)
        identity, _ = process_identity(child.pid)
        record.update(supervisor_pid=child.pid, supervisor_start=identity)
        save(record)
        time.sleep(1)
        if child.poll() is not None:
            error('supervisor_failed: see /var/lib/seinari-connect/service.log')
    # Verify our listener; no readiness assumption based only on a process existing.
    with socket.create_connection(('127.0.0.1', 22228), timeout=5) as conn:
        if not conn.recv(256).startswith(b'SSH-'):
            error('sshd_not_ready: local SSH listener did not answer')
    deadline = time.monotonic() + 30
    while True:
        try:
            if heartbeat().get('online') is True:
                break
        except Exception:
            pass
        if time.monotonic() >= deadline:
            error('tunnel_not_ready: the edge could not reach this machine; installation was rolled back')
        time.sleep(2)
    record = load()
    record['installed'] = True
    save(record)


def disconnect(rollback=False):
    record = load()
    remote_failed = False
    if record.get('token') and record.get('code'):
        try:
            post('stop', {'code': record['code']}, record['token'])
        except Exception as e:
            remote_failed = True
            print('Remote revoke failed; local access will still be removed: ' + str(e), file=sys.stderr)
    if record.get('mode') == 'systemd':
        subprocess.run(['systemctl', 'disable', '--now'] + UNITS, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    pid = record.get('supervisor_pid')
    if pid:
        identity, args = process_identity(pid)
        if identity == record.get('supervisor_start') and SELF.encode() in args and b'supervise' in args:
            os.killpg(pid, signal.SIGTERM)
            for _ in range(30):
                if process_identity(pid)[0] != identity:
                    break
                time.sleep(0.1)
            if process_identity(pid)[0] == identity:
                os.killpg(pid, signal.SIGKILL)
    # Delete only the account we created and its exact home, never a replacement user.
    try:
        user = pwd.getpwnam('seinari')
    except KeyError:
        user = None
    if user:
        if user.pw_uid != record.get('uid') or user.pw_dir != '/home/seinari':
            error('user_identity_changed: refusing to remove this account or its files')
        for entry in Path('/proc').iterdir():
            if not entry.name.isdigit():
                continue
            try:
                if entry.stat().st_uid == user.pw_uid:
                    os.kill(int(entry.name), signal.SIGKILL)
            except (ProcessLookupError, FileNotFoundError, PermissionError):
                pass
        subprocess.run(['userdel', '-r', 'seinari'], check=True)
    for unit in UNITS:
        Path('/etc/systemd/system', unit).unlink(missing_ok=True)
    Path('/etc/sudoers.d/seinari-connect').unlink(missing_ok=True)
    if record.get('mode') == 'systemd':
        subprocess.run(['systemctl', 'daemon-reload'], check=False)
    shutil.rmtree(STATE)
    Path(SELF).unlink(missing_ok=True)
    if not rollback:
        print('Disconnected. Seinari access, its account and local services have been removed.')
        if remote_failed:
            print('The offline server entry will expire independently; this machine no longer has a tunnel.')


def main():
    command = sys.argv[1] if len(sys.argv) > 1 else 'help'
    if command in ['help', '--help', '-h']:
        print('Usage: sudo seinari-connect stop\nDisconnect and remove Seinari access to this machine.')
        return
    if os.geteuid() != 0:
        if command == 'stop':
            os.execvp('sudo', ['sudo', SELF] + sys.argv[1:])
        error('root_required: use sudo seinari-connect ' + command)
    if command == 'enroll':
        enroll()
    elif command == 'claim-user':
        record = load()
        record['uid'] = pwd.getpwnam('seinari').pw_uid
        record['mode'] = 'systemd' if Path('/run/systemd/system').is_dir() and shutil.which('systemctl') else 'supervisor'
        save(record)
    elif command == 'start':
        start()
    elif command == 'sshd':
        os.execv(sshd_command()[0], sshd_command())
    elif command == 'tunnel':
        os.environ['AUTOSSH_GATETIME'] = '0'
        cmd = tunnel_command(load())
        os.execv(cmd[0], cmd)
    elif command == 'heartbeat':
        heartbeat()
    elif command == 'supervise':
        supervise()
    elif command == 'authorized-key':
        sys.stdout.write((STATE / 'authorized_keys').read_text())
    elif command == 'stop':
        disconnect('--rollback' in sys.argv)
    elif command == 'status':
        record = load()
        if not record.get('installed'):
            error('installation_incomplete: cleanup is required')
        print('Connection code: ' + record['code'])
    else:
        error('unknown_command: ' + command)


if __name__ == '__main__':
    try:
        main()
    except Exception as exc:
        print('seinari_connect_error: ' + str(exc), file=sys.stderr)
        sys.exit(1)
PYTHON
chmod 755 "$bin_tmp"
mv -f "$bin_tmp" "$bin"
useradd -m -U -d /home/seinari -s /bin/sh seinari
user_created=1
created_uid=$(id -u seinari)
"$bin" claim-user
printf 'seinari ALL=(ALL:ALL) NOPASSWD: ALL\n' > /etc/sudoers.d/seinari-connect
chmod 440 /etc/sudoers.d/seinari-connect
visudo -cf /etc/sudoers.d/seinari-connect >/dev/null
sudo -n -u seinari sudo -n true || fail 'sudo_grant_failed: the host sudo configuration did not accept the dedicated grant.'
ssh-keygen -q -t ed25519 -N '' -C seinari-connect-tunnel -f "$state/tunnel"
ssh-keygen -q -t ed25519 -N '' -C seinari-connect-host -f "$state/host"
printf '%s\n' "$invite_token" | "$bin" enroll
unset invite_token
cat > "$state/sshd_config" <<'SSHD'
Port 22228
ListenAddress 127.0.0.1
AddressFamily inet
HostKey /var/lib/seinari-connect/host
PidFile /var/lib/seinari-connect/sshd.pid
AllowUsers seinari
PermitRootLogin no
AuthenticationMethods publickey
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitEmptyPasswords no
HostbasedAuthentication no
AuthorizedKeysFile none
AuthorizedKeysCommand /usr/local/bin/seinari-connect authorized-key
AuthorizedKeysCommandUser root
UsePAM yes
PrintMotd no
Subsystem sftp internal-sftp
SSHD
# OpenSSH privilege separation needs this directory even without the distro service.
mkdir -p /run/sshd
chmod 755 /run/sshd
sshd -t -f "$state/sshd_config"
if [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1; then
    for role in sshd tunnel; do
        cat > "/etc/systemd/system/seinari-connect-$role.service" <<UNIT
[Unit]
Description=Seinari Connect $role
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/local/bin/seinari-connect $role
Restart=always
RestartSec=3
KillMode=control-group
[Install]
WantedBy=multi-user.target
UNIT
    done
    cat > /etc/systemd/system/seinari-connect-heartbeat.service <<'UNIT'
[Unit]
Description=Seinari Connect heartbeat
After=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/seinari-connect heartbeat
UNIT
    cat > /etc/systemd/system/seinari-connect-heartbeat.timer <<'UNIT'
[Unit]
Description=Seinari Connect heartbeat every minute
[Timer]
OnBootSec=15
OnUnitActiveSec=60
AccuracySec=1
[Install]
WantedBy=timers.target
UNIT
fi
"$bin" start
complete=1
"$bin" status
printf '\nInstalled: dedicated seinari account, passwordless sudo, admin-key-only SSH on localhost:22228, and an outbound encrypted tunnel.\nSeinari can administer this machine until you disconnect it.\nDisconnect: seinari-connect stop\n'
}
main "$@"; exit "$?"
ROOT_SCRIPT
if [ "$(id -u)" = 0 ]; then
    exec sh "$installer" "$@"
fi
if ! command -v sudo >/dev/null 2>&1; then
    rm -f "$installer"
    printf 'seinari_connect_error: sudo_missing: run this installer as root.\n' >&2
    exit 1
fi
if sudo -n true 2>/dev/null; then
    exec sudo sh "$installer" "$@"
fi
if [ -r /dev/tty ] && [ -w /dev/tty ]; then
    # shellcheck disable=SC2024 # The invoking user intentionally opens its own terminal.
    if sudo -v </dev/tty; then
        exec sudo sh "$installer" "$@"
    fi
fi
rm -f "$installer"
printf 'seinari_connect_error: sudo_authentication_failed: run from an interactive terminal, or run as root.\n' >&2
exit 1
}
main "$@"; exit "$?"
