#!/bin/sh
# LebotClaw Harness v0.4.0 source-snapshot installer. No sudo, Key or account input.
set -eu
LEBOT_ARCHIVE_URL='https://ailebot.cn/lebotclaw-download/downloads/LebotClaw-Harness-0.4.0-world-preview-source.zip'
LEBOT_EXPECTED_SHA='7d7a9b97fa6093e74fd04d194e2557734975b6f8ff2061eb7dc09e0f1b8a0721'
LEBOT_INSTALL_DIR="${HOME}/LebotClaw-Harness"
LEBOT_LOCAL_ARCHIVE=''
LEBOT_LAUNCH=1
LEBOT_DRY_RUN=0
while [ "$#" -gt 0 ]; do
  case "$1" in
    --dir) [ "$#" -ge 2 ] || exit 2; LEBOT_INSTALL_DIR="$2"; shift 2 ;;
    --archive) [ "$#" -ge 2 ] || exit 2; LEBOT_LOCAL_ARCHIVE="$2"; shift 2 ;;
    --no-launch) LEBOT_LAUNCH=0; shift ;;
    --dry-run) LEBOT_DRY_RUN=1; shift ;;
    --help) printf '%s\n' 'Usage: sh install-harness.sh [--dir PATH] [--archive LOCAL_ZIP] [--no-launch] [--dry-run]'; exit 0 ;;
    *) printf '%s\n' "Unknown argument: $1" >&2; exit 2 ;;
  esac
done
LEBOT_PYTHON=$(command -v python3 || true)
if [ -z "$LEBOT_PYTHON" ]; then printf '%s\n' 'Please install Python 3.9+ first.' >&2; exit 1; fi
"$LEBOT_PYTHON" -c 'import sys; assert sys.version_info >= (3,9), "Python 3.9+ required"'
if [ -e "$LEBOT_INSTALL_DIR" ] || [ -L "$LEBOT_INSTALL_DIR" ]; then
  printf '%s\n' "Directory already exists; nothing overwritten: $LEBOT_INSTALL_DIR" >&2; exit 1
fi
if [ "$LEBOT_DRY_RUN" -eq 1 ]; then
  printf '%s\n' "Source: $LEBOT_ARCHIVE_URL" "SHA256: $LEBOT_EXPECTED_SHA" "Directory: $LEBOT_INSTALL_DIR" 'Plan: verify ZIP, create venv, install dependencies/Chromium, open local UI.'; exit 0
fi
LEBOT_TEMP_DIR=$(mktemp -d "${TMPDIR:-/tmp}/lebotclaw-install.XXXXXXXX")
trap 'rm -rf "$LEBOT_TEMP_DIR"' EXIT HUP INT TERM
LEBOT_ZIP="$LEBOT_TEMP_DIR/source.zip"
if [ -n "$LEBOT_LOCAL_ARCHIVE" ]; then cp "$LEBOT_LOCAL_ARCHIVE" "$LEBOT_ZIP";
else
  command -v curl >/dev/null 2>&1 || { printf '%s\n' 'curl is required.' >&2; exit 1; }
  curl --fail --location --proto '=https' --proto-redir '=https' --retry 2 --connect-timeout 15 --max-time 300 "$LEBOT_ARCHIVE_URL" -o "$LEBOT_ZIP"
fi
"$LEBOT_PYTHON" - "$LEBOT_ZIP" "$LEBOT_EXPECTED_SHA" "$LEBOT_TEMP_DIR" "$LEBOT_INSTALL_DIR" <<'PY'
import hashlib,os,shutil,stat,sys,zipfile
from pathlib import Path,PurePosixPath
archive,digest,temp,destination=sys.argv[1:]
if hashlib.sha256(Path(archive).read_bytes()).hexdigest()!=digest:
    raise SystemExit('Checksum mismatch; source not installed.')
root=Path(temp)/'unpacked';root.mkdir()
with zipfile.ZipFile(archive) as z:
    for entry in z.infolist():
        path=PurePosixPath(entry.filename)
        if path.is_absolute() or '..' in path.parts or not path.parts or path.parts[0]!='LebotClaw-Harness' or '\\' in entry.filename or stat.S_ISLNK(entry.external_attr>>16):
            raise SystemExit('Unsafe archive path; source not installed.')
    z.extractall(root)
target=Path(destination).expanduser().absolute()
target.parent.mkdir(parents=True,exist_ok=True)
if target.exists() or target.is_symlink():raise SystemExit('Directory already exists; nothing overwritten.')
target.mkdir()  # Reserve without overwriting another process or existing files.
try:
    for child in (root/'LebotClaw-Harness').iterdir():shutil.move(str(child),str(target/child.name))
except Exception:
    raise SystemExit('Extraction failed; partial install kept for inspection.')
print('Source checksum passed; installed at '+str(target))
PY
cd "$LEBOT_INSTALL_DIR"
"$LEBOT_PYTHON" -m venv .venv
.venv/bin/python -m pip install --upgrade pip
.venv/bin/python -m pip install -e '.[browser]'
.venv/bin/python -m playwright install chromium --only-shell
printf '%s\n' 'Installation complete. Enter your DeepSeek Key in the local UI, not this terminal.' 'Next start: sh scripts/start.sh'
rm -rf "$LEBOT_TEMP_DIR"
trap - EXIT HUP INT TERM
if [ "$LEBOT_LAUNCH" -eq 1 ]; then exec .venv/bin/python -m lebotclaw_harness web --open; fi
