#!/usr/bin/env python3
"""Run a Break The Root room package locally, the way the platform deploys it.

The runner validates a room package against the submission guidelines,
builds its Dockerfile and starts one disposable room on localhost.  It follows
the platform contract for dynamic rooms: per-instance red flags are mounted
read-only at /opt/seed-flags, remediation checks are mounted read-only at
/opt/btr/checks, and SSH credentials are injected as SSH_USERNAME and
SSH_PASSWORD.  The local SSH password always comes from --ssh-password or
BTR_LOCAL_SSH_PASSWORD, never from the manifest.

PACKAGE can be either:
  * an unzipped package folder (Dockerfile, entrypoint.sh, app/, flags/,
    checks/ and a manifest.json or <slug>-manifest.json at its root), or
  * the exact backend ZIP you will submit.  The manifest is read from
    --manifest, or from a *-manifest.json next to the ZIP.

Examples:
  python3 tools/local-room.py /path/to/room-folder --validate
  python3 tools/local-room.py /path/to/room-backend.zip --manifest room-manifest.json
  python3 tools/local-room.py /path/to/room-folder --check 1
  python3 tools/local-room.py /path/to/room-folder --stop
"""

from __future__ import annotations

import argparse
import json
import os
import re
import shutil
import socket
import stat
import subprocess
import sys
import time
import urllib.error
import urllib.request
import zipfile
from pathlib import Path, PurePosixPath
from typing import NoReturn

SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$")
FLAG_RE = re.compile(r"^BTR\{[^\r\n{}]+\}$")
CONTAINER_NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$")
CHECK_TIMEOUT_SECONDS = 10
CACHE_ROOT = Path(
    os.environ.get("BTR_LOCAL_CACHE", Path.home() / ".cache" / "btr-local-room")
)


# --------------------------------------------------------------------------
# helpers
# --------------------------------------------------------------------------

def fail(message: str) -> NoReturn:
    raise SystemExit(f"local-room: error: {message}")


def warn(message: str) -> None:
    print(f"local-room: warning: {message}", file=sys.stderr)


def require_docker() -> None:
    if shutil.which("docker") is None:
        fail("Docker is not installed or is not on PATH.")


def docker(*args: str, check: bool = True, env: dict | None = None) -> subprocess.CompletedProcess[str]:
    require_docker()
    result = subprocess.run(["docker", *args], text=True, check=False, env=env)
    if check and result.returncode:
        fail(f"docker {args[0]} failed with exit code {result.returncode}")
    return result


def docker_quiet(*args: str) -> subprocess.CompletedProcess[str]:
    require_docker()
    return subprocess.run(
        ["docker", *args],
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        check=False,
    )


def container_exists(name: str) -> bool:
    return docker_quiet("container", "inspect", name).returncode == 0


def container_running(name: str) -> bool:
    result = docker_quiet("container", "inspect", "--format", "{{.State.Running}}", name)
    return result.returncode == 0 and result.stdout.strip() == "true"


def image_exists(image: str) -> bool:
    return docker_quiet("image", "inspect", image).returncode == 0


def port_in_use(port: int) -> bool:
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
        probe.settimeout(0.2)
        try:
            probe.connect(("127.0.0.1", port))
            return True
        except OSError:
            return False


# --------------------------------------------------------------------------
# manifest
# --------------------------------------------------------------------------

def read_manifest(path: Path) -> dict:
    try:
        value = json.loads(path.read_text(encoding="utf-8"))
    except OSError as exc:
        fail(f"cannot read manifest {path}: {exc}")
    except json.JSONDecodeError as exc:
        fail(f"manifest {path} is not valid JSON: {exc}")
    if not isinstance(value, dict):
        fail(f"manifest {path} must be a JSON object")
    return value


def find_manifest_in_dir(folder: Path) -> Path:
    candidates = []
    if (folder / "manifest.json").is_file():
        candidates.append(folder / "manifest.json")
    candidates.extend(sorted(folder.glob("*-manifest.json")))
    if not candidates:
        fail(
            f"no manifest.json or <slug>-manifest.json at the root of {folder}; "
            "put the manifest next to the Dockerfile for local testing"
        )
    if len(candidates) > 1:
        names = ", ".join(path.name for path in candidates)
        fail(f"more than one manifest in {folder} ({names}); keep exactly one")
    return candidates[0]


def find_manifest_for_zip(zip_path: Path) -> Path:
    folder = zip_path.parent
    stem = zip_path.stem
    if stem.endswith("-backend"):
        guess = folder / f"{stem[: -len('-backend')]}-manifest.json"
        if guess.is_file():
            return guess
    candidates = sorted(folder.glob("*-manifest.json"))
    if len(candidates) == 1:
        return candidates[0]
    if not candidates:
        fail(f"no *-manifest.json next to {zip_path.name}; pass --manifest PATH")
    fail(f"several *-manifest.json files next to {zip_path.name}; pass --manifest PATH")


def validate_manifest(manifest: dict, errors: list[str], warnings: list[str]) -> None:
    slug = manifest.get("slug")
    if not isinstance(slug, str) or not SLUG_RE.fullmatch(slug):
        errors.append(
            "manifest slug must be 3-64 characters of lowercase letters, numbers "
            "and hyphens, starting and ending with a letter or number"
        )

    port = manifest.get("container_port")
    if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535:
        errors.append("manifest container_port must be an integer between 1 and 65535")

    for key in ("required_flags", "extra_checks"):
        value = manifest.get(key, [])
        if not isinstance(value, list):
            errors.append(f"manifest {key} must be a list")
            continue
        seen: set[int] = set()
        for entry in value:
            if not isinstance(entry, dict) or not isinstance(entry.get("id"), int):
                errors.append(f"every manifest {key} entry needs an integer id")
                continue
            entry_id = entry["id"]
            # The platform serves red-flag1..4 and runs check1.sh..check4.sh;
            # any other id deploys fine and is then ungradeable.
            if isinstance(entry_id, bool) or not 1 <= entry_id <= 4:
                errors.append(
                    f"manifest {key} id {entry_id!r} is out of range: ids must be 1, 2, 3 or 4"
                )
            elif entry_id in seen:
                errors.append(f"manifest {key} repeats id {entry_id}")
            else:
                seen.add(entry_id)

    if manifest.get("visibility") not in (None, "draft"):
        warnings.append('manifest visibility should be "draft" for submissions')

    if manifest.get("guided") is False:
        url = manifest.get("writeup_url")
        if not isinstance(url, str) or not url.startswith("https://"):
            warnings.append("unguided rooms need an HTTPS writeup_url in the manifest")

    overview = manifest.get("catalog_overview")
    if isinstance(overview, str) and len(overview) > 500:
        errors.append("manifest catalog_overview is longer than 500 characters")


def ids(manifest: dict, key: str) -> list[int]:
    value = manifest.get(key, [])
    if not isinstance(value, list):
        return []
    return [entry["id"] for entry in value if isinstance(entry, dict) and isinstance(entry.get("id"), int)]


# --------------------------------------------------------------------------
# package
# --------------------------------------------------------------------------

def validate_flag_file(path: Path, errors: list[str]) -> None:
    try:
        raw = path.read_bytes()
    except OSError as exc:
        errors.append(f"cannot read {path.name}: {exc}")
        return
    try:
        text = raw.decode("utf-8")
    except UnicodeDecodeError:
        errors.append(f"{path.parent.name}/{path.name} is not valid UTF-8")
        return
    if text.endswith("\r\n"):
        text = text[:-2]
    elif text.endswith("\n"):
        text = text[:-1]
    if "\n" in text or "\r" in text:
        errors.append(f"{path.parent.name}/{path.name} must contain exactly one line")
    elif not FLAG_RE.fullmatch(text):
        errors.append(
            f"{path.parent.name}/{path.name} must contain exactly one flag like "
            "BTR{example_flag_value}, with no quotes or extra text"
        )


def is_executable(path: Path) -> bool:
    return bool(path.stat().st_mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))


def validate_package(package: Path, manifest: dict, *, from_zip: bool) -> None:
    errors: list[str] = []
    warnings: list[str] = []

    validate_manifest(manifest, errors, warnings)

    if not (package / "Dockerfile").is_file():
        nested = [p for p in package.rglob("Dockerfile")]
        if nested:
            errors.append(
                f"Dockerfile must be at the package root, found it at "
                f"{nested[0].relative_to(package)} (remove the wrapper folder)"
            )
        else:
            errors.append("Dockerfile is missing from the package root")

    entrypoint = package / "entrypoint.sh"
    if not entrypoint.is_file():
        errors.append("entrypoint.sh is missing from the package root")
    elif not is_executable(entrypoint):
        warnings.append(
            "entrypoint.sh is not executable; make sure the Dockerfile runs chmod 0755 on it"
        )

    if not (package / "app").is_dir():
        warnings.append("app/ folder is missing from the package root")

    flags_dir = package / "flags"
    for number in sorted(set([1, 2] + ids(manifest, "required_flags"))):
        path = flags_dir / f"red-flag{number}.txt"
        if not path.is_file():
            errors.append(f"flags/red-flag{number}.txt is missing")
        else:
            validate_flag_file(path, errors)

    checks_dir = package / "checks"
    declared_checks = ids(manifest, "extra_checks")
    for number in declared_checks:
        check = checks_dir / f"check{number}.sh"
        blue = flags_dir / f"blue-flag{number}.txt"
        if not check.is_file():
            errors.append(f"checks/check{number}.sh is missing (declared in extra_checks)")
        elif not is_executable(check):
            errors.append(
                f"checks/check{number}.sh is not executable; run chmod +x checks/*.sh"
                + (" and re-create the ZIP on Linux or macOS" if from_zip else "")
            )
        if not blue.is_file():
            errors.append(f"flags/blue-flag{number}.txt is missing (declared in extra_checks)")
        else:
            validate_flag_file(blue, errors)

    if checks_dir.is_dir():
        for extra in sorted(checks_dir.glob("check*.sh")):
            match = re.fullmatch(r"check([0-9]+)\.sh", extra.name)
            if match and int(match.group(1)) not in declared_checks:
                errors.append(f"checks/{extra.name} is not declared in the manifest's extra_checks")

    for name in ("manifest.json",):
        if from_zip and (package / name).exists():
            errors.append(f"the backend ZIP must not contain {name}")

    for message in warnings:
        warn(message)
    if errors:
        print("local-room: the package does not meet the submission guidelines:", file=sys.stderr)
        # One mistake can raise the same complaint twice -- a repeated check id
        # reports its missing files once per entry. Say each thing once.
        for message in dict.fromkeys(errors):
            print(f"  - {message}", file=sys.stderr)
        raise SystemExit(1)


def extract_zip(zip_path: Path, slug: str) -> Path:
    """Validate the ZIP layout and extract it to a stable per-room folder."""
    try:
        archive = zipfile.ZipFile(zip_path)
    except (OSError, zipfile.BadZipFile) as exc:
        fail(f"{zip_path} is not a valid ZIP file: {exc}")

    with archive:
        names = archive.namelist()
        problems = []
        for name in names:
            pure = PurePosixPath(name)
            if pure.is_absolute() or ".." in pure.parts or "\\" in name:
                fail(f"unsafe path in ZIP: {name}")
            if name.lower().endswith(".zip"):
                problems.append(f"the ZIP contains another ZIP ({name}); remove it")
            if pure.name.endswith("manifest.json"):
                problems.append(f"the ZIP must not contain a manifest ({name}); send it separately")

        roots = {PurePosixPath(name).parts[0] for name in names if name.strip("/")}
        if "Dockerfile" not in names:
            wrapped = [name for name in names if PurePosixPath(name).name == "Dockerfile"]
            if wrapped:
                problems.append(
                    f"Dockerfile is inside a wrapper folder ({wrapped[0]}); zip the folder's "
                    "contents, not the folder itself"
                )
            else:
                problems.append("the ZIP has no Dockerfile at its root")
        if len(roots) == 1 and "Dockerfile" not in roots and not any(
            "wrapper folder" in message for message in problems
        ):
            problems.append(f"everything in the ZIP is inside one folder ({next(iter(roots))}/)")

        if problems:
            print("local-room: the backend ZIP does not meet the submission guidelines:", file=sys.stderr)
            for message in dict.fromkeys(problems):
                print(f"  - {message}", file=sys.stderr)
            raise SystemExit(1)

        target = CACHE_ROOT / slug / "package"
        if target.exists():
            shutil.rmtree(target)
        target.mkdir(parents=True)
        for info in archive.infolist():
            destination = target / info.filename
            if info.is_dir():
                destination.mkdir(parents=True, exist_ok=True)
                continue
            destination.parent.mkdir(parents=True, exist_ok=True)
            with archive.open(info) as source, open(destination, "wb") as out:
                shutil.copyfileobj(source, out)
            mode = (info.external_attr >> 16) & 0o777
            if mode:
                destination.chmod(mode)
    return target


def resolve_package(path: Path, manifest_arg: Path | None) -> tuple[Path, dict, bool]:
    """Return (package folder, manifest, came_from_zip)."""
    if path.is_file() and path.suffix.lower() == ".zip":
        manifest_path = manifest_arg or find_manifest_for_zip(path)
        manifest = read_manifest(manifest_path.expanduser().resolve())
        slug = manifest.get("slug")
        if not isinstance(slug, str) or not SLUG_RE.fullmatch(slug):
            fail("manifest slug is missing or invalid")
        return extract_zip(path, slug), manifest, True

    if not path.is_dir():
        fail(f"package does not exist or is not a folder/ZIP: {path}")
    manifest_path = manifest_arg.expanduser().resolve() if manifest_arg else find_manifest_in_dir(path)
    manifest = read_manifest(manifest_path)
    slug = manifest.get("slug")
    if not isinstance(slug, str) or not SLUG_RE.fullmatch(slug):
        fail("manifest slug is missing or invalid")
    return path, manifest, False


def cached_package(slug: str) -> Path | None:
    folder = CACHE_ROOT / slug / "package"
    return folder if folder.is_dir() else None


def container_name(slug: str, requested: str | None) -> str:
    name = requested or f"btr-local-{slug}"
    if not CONTAINER_NAME_RE.fullmatch(name):
        fail("container name contains unsupported characters")
    return name


# --------------------------------------------------------------------------
# start
# --------------------------------------------------------------------------

def http_probe(port: int) -> tuple[int, str] | None:
    """Return (status, path) for the first HTTP answer from /health or /."""
    for path in ("/health", "/"):
        try:
            with urllib.request.urlopen(f"http://127.0.0.1:{port}{path}", timeout=2) as response:
                return response.status, path
        except urllib.error.HTTPError as exc:
            if path == "/health" and exc.code == 404:
                continue
            return exc.code, path
        except (urllib.error.URLError, TimeoutError, OSError):
            continue
    return None


def wait_until_ready(name: str, port: int, timeout: float) -> tuple[int, str] | None:
    """Wait for a real HTTP answer.  Docker accepts TCP on a published port
    before the app listens, so a TCP connect alone proves nothing."""
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        if not container_running(name):
            return None
        answer = http_probe(port)
        if answer is not None:
            return answer
        time.sleep(0.5)
    return None


def start(
    package: Path,
    manifest: dict,
    name: str,
    port: int,
    ssh_port: int,
    ssh_enabled: bool,
    ssh_username: str,
    ssh_password: str,
    rebuild: bool,
    replace: bool,
    legacy_build: bool,
    timeout: float,
    original: Path,
) -> int:
    slug = manifest["slug"]
    image = f"btr-local-{slug}:latest"
    container_port = manifest.get("container_port", 8080)

    # Remove our own old container first, so its ports don't look "in use".
    if container_exists(name):
        if not replace:
            fail(f"container {name!r} already exists; use --replace or --stop")
        docker("rm", "-f", name)

    if port_in_use(port):
        fail(f"local web port {port} is already in use; stop that service or use --port")
    if ssh_enabled and port_in_use(ssh_port):
        fail(f"local SSH port {ssh_port} is already in use; stop that service or use --ssh-port")

    if rebuild or not image_exists(image):
        env = None
        if legacy_build:
            env = dict(os.environ, DOCKER_BUILDKIT="0")
        docker("build", "--pull=false", "--tag", image, str(package), env=env)

    command = [
        "run", "--detach", "--name", name,
        "--label", "btr.local=true",
        "--label", f"btr.lab={slug}",
        "--memory", "512m",
        "--cpus", "1",
        "--pids-limit", "128",
        "--cap-drop", "ALL",
        "--cap-add", "DAC_OVERRIDE",
        "--cap-add", "CHOWN",
        "--cap-add", "FOWNER",
        "--cap-add", "SETUID",
        "--cap-add", "SETGID",
        "--tmpfs", "/run:rw,noexec,nosuid,size=16m",
        "--tmpfs", "/tmp:rw,noexec,nosuid,size=64m",
        "--publish", f"127.0.0.1:{port}:{container_port}",
    ]

    if ssh_enabled:
        # sshd's privilege separation needs chroot, and PAM login needs audit.
        command.extend(["--publish", f"127.0.0.1:{ssh_port}:22"])
        command.extend(["--cap-add", "AUDIT_WRITE", "--cap-add", "SYS_CHROOT"])
        command.extend([
            "--env", f"SSH_USERNAME={ssh_username}",
            "--env", "SSH_PASSWORD",
        ])
    if not manifest.get("privilege_escalation"):
        command.extend(["--security-opt", "no-new-privileges:true"])

    checks = package / "checks"
    if checks.is_dir():
        command.extend(["--volume", f"{checks.resolve()}:/opt/btr/checks:ro"])

    for number in sorted(set([1, 2] + ids(manifest, "required_flags"))):
        path = package / "flags" / f"red-flag{number}.txt"
        command.extend(["--volume", f"{path.resolve()}:/opt/seed-flags/red-flag{number}.txt:ro"])

    command.append(image)
    # The password goes through the environment, not the command line,
    # so it doesn't show up in `ps` on the host.
    run_env = dict(os.environ, SSH_PASSWORD=ssh_password) if ssh_enabled else None
    docker(*command, env=run_env)

    answer = wait_until_ready(name, port, timeout)
    if answer is None:
        if container_running(name):
            print(
                f"local-room: {name} is running, but the app did not answer HTTP on port "
                f"{port} within {timeout:.0f} seconds. Check that it listens on "
                f"0.0.0.0:{container_port}. Logs:",
                file=sys.stderr,
            )
        else:
            print(f"local-room: {name} exited during startup. Logs:", file=sys.stderr)
        docker("logs", "--tail", "100", name, check=False)
        return 1

    status, path = answer
    print(f"Room started: {manifest.get('name', slug)} ({slug})")
    print(f"Web:        http://127.0.0.1:{port}/")
    if ssh_enabled:
        print(f"SSH:        ssh -p {ssh_port} {ssh_username}@127.0.0.1")
        print("Password:   the one you supplied locally")
    print(f"Container:  {name}")
    print(f"Image:      {image}")
    print(f"Probe:      HTTP {status} on {path}")
    print(f"Logs:       docker logs -f {name}")
    print(f"Stop:       python3 tools/local-room.py {original} --stop")
    if status >= 500:
        warn(f"the app answered with HTTP {status}; check the logs")
    return 0


# --------------------------------------------------------------------------
# checks
# --------------------------------------------------------------------------

def run_check(package: Path, name: str, check_id: int) -> int:
    check_path = package / "checks" / f"check{check_id}.sh"
    blue_path = package / "flags" / f"blue-flag{check_id}.txt"
    if not check_path.is_file():
        fail(f"missing checks/check{check_id}.sh")
    if not blue_path.is_file():
        fail(f"missing flags/blue-flag{check_id}.txt")
    if not container_running(name):
        fail(f"container {name!r} is not running; start the room first")

    result = docker_quiet(
        "exec", name,
        "/usr/bin/timeout", str(CHECK_TIMEOUT_SECONDS),
        f"/opt/btr/checks/check{check_id}.sh",
    )
    output = result.stdout.rstrip("\r\n")
    passed = result.returncode == 0 and output == "true"

    print(f"Check {check_id}: {'passed' if passed else 'failed'}")
    if result.returncode == 124:
        print(f"  reason: timed out after {CHECK_TIMEOUT_SECONDS} seconds", file=sys.stderr)
    elif result.returncode in (126, 127) and "timeout" in (result.stderr or ""):
        print("  reason: /usr/bin/timeout is missing from the image (install coreutils)", file=sys.stderr)
    elif result.returncode == 126:
        print("  reason: the check is not executable (chmod +x checks/*.sh, then restart)", file=sys.stderr)
    elif result.returncode == 0 and output not in ("true", "false"):
        print(f"  reason: output must be exactly 'true' or 'false', got {output!r}", file=sys.stderr)
    if result.stderr.strip():
        print(result.stderr.strip(), file=sys.stderr)

    if not passed:
        return 1
    print(f"Remediation flag {check_id}: {blue_path.read_text(encoding='utf-8').strip()}")
    return 0


# --------------------------------------------------------------------------
# main
# --------------------------------------------------------------------------

def main() -> int:
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument("package", type=Path, help="room package folder or backend ZIP")
    parser.add_argument("--manifest", type=Path, help="manifest path (required for a ZIP unless one sits next to it)")
    parser.add_argument("--port", type=int, default=8080, help="local web port (default: 8080)")
    parser.add_argument("--ssh-port", type=int, default=2222, help="local SSH port (default: 2222)")
    parser.add_argument("--ssh", action="store_true", help="enable local SSH even if the manifest does not")
    parser.add_argument("--ssh-username", help="local SSH username (default: manifest ssh_username, challenge_username, then app)")
    parser.add_argument("--ssh-password", help="local SSH password; prefer BTR_LOCAL_SSH_PASSWORD")
    parser.add_argument("--name", help="Docker container name (default: btr-local-<slug>)")
    parser.add_argument("--replace", action="store_true", help="remove an existing container with this name first")
    parser.add_argument("--rebuild", action="store_true", help="always rebuild the Docker image")
    parser.add_argument("--legacy-build", action="store_true", help="build with the legacy builder (DOCKER_BUILDKIT=0)")
    parser.add_argument("--timeout", type=float, default=60, help="seconds to wait for the app to answer (default: 60)")
    parser.add_argument("--validate", action="store_true", help="only validate the package, do not start it")
    parser.add_argument("--stop", action="store_true", help="stop and remove the room container")
    parser.add_argument("--check", type=int, metavar="N", help="run checks/checkN.sh and print blue-flagN.txt if it passes")
    args = parser.parse_args()

    original = args.package
    path = args.package.expanduser().resolve()
    manifest_arg = args.manifest.expanduser().resolve() if args.manifest else None

    # --stop and --check on a ZIP reuse the copy extracted at start time.
    if path.is_file() and path.suffix.lower() == ".zip" and (args.stop or args.check is not None):
        manifest = read_manifest(manifest_arg or find_manifest_for_zip(path))
        slug = manifest.get("slug")
        if not isinstance(slug, str) or not SLUG_RE.fullmatch(slug):
            fail("manifest slug is missing or invalid")
        package = cached_package(slug)
        from_zip = True
    else:
        package, manifest, from_zip = resolve_package(path, manifest_arg)

    name = container_name(manifest["slug"], args.name)

    if args.stop:
        docker("rm", "-f", name, check=False)
        print(f"Stopped/removed {name}")
        return 0

    if args.check is not None:
        if package is None:
            fail("start the room from this ZIP first; there is no extracted copy yet")
        return run_check(package, name, args.check)

    validate_package(package, manifest, from_zip=from_zip)
    if args.validate:
        print(f"Package OK: {manifest.get('name', manifest['slug'])} ({manifest['slug']})")
        return 0

    for value in (args.port, args.ssh_port):
        if not 1 <= value <= 65535:
            fail("ports must be between 1 and 65535")

    ssh_enabled = bool(manifest.get("ssh_enabled")) or args.ssh
    ssh_username = (
        args.ssh_username
        or manifest.get("ssh_username")
        or manifest.get("challenge_username")
        or "app"
    )
    ssh_password = args.ssh_password or os.environ.get("BTR_LOCAL_SSH_PASSWORD", "")
    if ssh_enabled and not ssh_password:
        fail("SSH is enabled but no password was supplied; set BTR_LOCAL_SSH_PASSWORD or use --ssh-password")

    return start(
        package,
        manifest,
        name,
        args.port,
        args.ssh_port,
        ssh_enabled,
        ssh_username,
        ssh_password,
        args.rebuild,
        args.replace,
        args.legacy_build,
        args.timeout,
        original,
    )


if __name__ == "__main__":
    raise SystemExit(main())
