#!/bin/bash
# OriginReach installer — PEP 668 safe, Ubuntu 18.04+ and other Linux ~2018+.
# One-liner:
#   curl -fsSL https://cli.tacticaldataconcepts.com/install.sh | bash
# Enroll + systemd/cron service:
#   curl -fsSL https://cli.tacticaldataconcepts.com/install.sh | sudo bash -s -- --token orva_…
set -euo pipefail

VERSION_FALLBACK="0.2.1"
DEFAULT_BASE="https://cli.tacticaldataconcepts.com"
DEFAULT_URL="https://originreach.tacticaldataconcepts.com"
MIN_PY_MAJOR=3
MIN_PY_MINOR=10

BASE="${ORIGINREACH_INSTALL_BASE:-$DEFAULT_BASE}"
DASH_URL="${ORIGINREACH_URL:-}"
TOKEN="${ORIGINREACH_TOKEN:-}"
PREFIX="${ORIGINREACH_PREFIX:-}"
ASSUME_YES=0
FORCE_USER=0
WANT_SERVICE=""   # empty=ask, 1=yes, 0=no
WANT_UPDATE=""    # empty=ask (default yes), 1=yes, 0=no
TOKEN_SET=0
DETECT_ONLY=0
BINDIR=""
PYTHON=""
PYTHON_VERSION=""
INIT_SYS=""
OS_ID=""
OS_VERSION=""
OS_LIKE=""
INSTALL_MODE=""   # venv | onefile
REMOTE_VERSION=""
IS_ROOT=0

usage() {
  cat <<'EOF'
OriginReach installer

Usage:
  curl -fsSL https://cli.tacticaldataconcepts.com/install.sh | bash
  curl -fsSL https://cli.tacticaldataconcepts.com/install.sh | sudo bash -s -- --token orva_YOUR_TOKEN

Options:
  --token TOKEN       Dashboard agent token (or ORIGINREACH_TOKEN).
                      Implies --service and --auto-update unless overridden.
  --url URL           Dashboard URL (default https://originreach.tacticaldataconcepts.com)
  --prefix DIR        Install prefix (root: /opt/originreach,
                      user: ~/.local/share/originreach)
  --bindir DIR        Directory for the originreach symlink
  --service           Install a background agent (systemd, OpenRC, or cron)
  --no-service        CLI only
  --auto-update       Daily self-update (default: yes)
  --no-auto-update    Skip the updater
  --user              Force a user-local install (no root packages)
  --yes, -y           Non-interactive; accept defaults
  --detect            Print detected OS/python/init and exit
  -h, --help          Show this help

The installer never runs system pip. It uses a dedicated venv (PEP 668).
On Python older than 3.10 it falls back to the one-file agent.
EOF
}

log() { printf 'originreach-install: %s\n' "$*" >&2; }
die() { printf 'originreach-install: error: %s\n' "$*" >&2; exit 1; }

have() { command -v "$1" >/dev/null 2>&1; }

is_root() { [ "$(id -u)" -eq 0 ]; }

parse_args() {
  while [ $# -gt 0 ]; do
    case "$1" in
      --token)
        [ $# -ge 2 ] || die "--token needs a value"
        TOKEN=$2
        TOKEN_SET=1
        shift 2
        ;;
      --token=*)
        TOKEN=${1#--token=}
        TOKEN_SET=1
        shift
        ;;
      --url)
        [ $# -ge 2 ] || die "--url needs a value"
        DASH_URL=$2
        shift 2
        ;;
      --url=*)
        DASH_URL=${1#--url=}
        shift
        ;;
      --prefix)
        [ $# -ge 2 ] || die "--prefix needs a value"
        PREFIX=$2
        shift 2
        ;;
      --prefix=*)
        PREFIX=${1#--prefix=}
        shift
        ;;
      --bindir)
        [ $# -ge 2 ] || die "--bindir needs a value"
        BINDIR=$2
        shift 2
        ;;
      --bindir=*)
        BINDIR=${1#--bindir=}
        shift
        ;;
      --service) WANT_SERVICE=1; shift ;;
      --no-service) WANT_SERVICE=0; shift ;;
      --auto-update) WANT_UPDATE=1; shift ;;
      --no-auto-update) WANT_UPDATE=0; shift ;;
      --user) FORCE_USER=1; shift ;;
      --yes|-y) ASSUME_YES=1; shift ;;
      --detect) DETECT_ONLY=1; shift ;;
      -h|--help) usage; exit 0 ;;
      --) shift; break ;;
      *) die "unknown option: $1 (try --help)" ;;
    esac
  done
  if [ -n "$TOKEN" ]; then
    TOKEN_SET=1
  fi
  if [ "$TOKEN_SET" -eq 1 ] && [ -z "$DASH_URL" ]; then
    DASH_URL=$DEFAULT_URL
  fi
  if [ "$TOKEN_SET" -eq 1 ] && [ -z "$WANT_SERVICE" ]; then
    WANT_SERVICE=1
  fi
  if [ "$TOKEN_SET" -eq 1 ] && [ -z "$WANT_UPDATE" ]; then
    WANT_UPDATE=1
  fi
}

read_os() {
  OS_ID=unknown
  OS_VERSION=""
  OS_LIKE=""
  if [ -r /etc/os-release ]; then
    # shellcheck disable=SC1091
    . /etc/os-release
    OS_ID=${ID:-unknown}
    OS_VERSION=${VERSION_ID:-}
    OS_LIKE=${ID_LIKE:-}
  elif [ -r /etc/redhat-release ]; then
    OS_ID=rhel
  fi
}

detect_init() {
  if [ -d /run/systemd/system ] && have systemctl; then
    INIT_SYS=systemd
  elif have rc-update && { have rc-service || [ -x /sbin/openrc-run ]; }; then
    INIT_SYS=openrc
  elif [ -d /etc/cron.d ] || have crontab; then
    INIT_SYS=cron
  else
    INIT_SYS=none
  fi
}

py_meets() {
  local bin=$1
  [ -n "$bin" ] && have "$bin" || return 1
  "$bin" -c "import sys; raise SystemExit(0 if sys.version_info[:2] >= (${MIN_PY_MAJOR}, ${MIN_PY_MINOR}) else 1)" 2>/dev/null
}

find_python() {
  local c
  PYTHON=""
  PYTHON_VERSION=""
  for c in python3.14 python3.13 python3.12 python3.11 python3.10 python3; do
    if py_meets "$c"; then
      PYTHON=$(command -v "$c")
      PYTHON_VERSION=$("$PYTHON" -c 'import sys; print("%d.%d" % sys.version_info[:2])')
      return 0
    fi
  done
  if have python3; then
    PYTHON=$(command -v python3)
    PYTHON_VERSION=$("$PYTHON" -c 'import sys; print("%d.%d" % sys.version_info[:2])' 2>/dev/null || echo "0.0")
  fi
  return 1
}

fetch() {
  # fetch URL DEST
  local url=$1 dest=$2
  if have curl; then
    curl -fsSL --retry 3 --retry-delay 1 -o "$dest" "$url"
  elif have wget; then
    wget -q --tries=3 -O "$dest" "$url"
  else
    die "need curl or wget"
  fi
}

fetch_stdout() {
  local url=$1
  if have curl; then
    curl -fsSL --retry 3 --retry-delay 1 "$url"
  elif have wget; then
    wget -q --tries=3 -O - "$url"
  else
    die "need curl or wget"
  fi
}

file_sha256() {
  if have sha256sum; then
    sha256sum "$1" | awk '{print $1}'
  elif have shasum; then
    shasum -a 256 "$1" | awk '{print $1}'
  elif have openssl; then
    openssl dgst -sha256 "$1" | awk '{print $NF}'
  else
    echo ""
  fi
}

ask_yn() {
  # ask_yn "prompt" default(Y|N)
  local prompt=$1 def=$2 reply=""
  if [ "$ASSUME_YES" -eq 1 ]; then
    [ "$def" = Y ]
    return
  fi
  if [ -r /dev/tty ]; then
    printf '%s' "$prompt" > /dev/tty
    IFS= read -r reply < /dev/tty || true
  fi
  if [ -z "$reply" ]; then
    reply=$def
  fi
  case "$reply" in
    [Yy]|[Yy][Ee][Ss]) return 0 ;;
    *) return 1 ;;
  esac
}

set_defaults() {
  if is_root && [ "$FORCE_USER" -eq 0 ]; then
    IS_ROOT=1
  else
    IS_ROOT=0
  fi
  if [ -z "$PREFIX" ]; then
    if [ "$IS_ROOT" -eq 1 ]; then
      PREFIX=/opt/originreach
    else
      PREFIX="${XDG_DATA_HOME:-$HOME/.local/share}/originreach"
    fi
  fi
  if [ -z "$BINDIR" ]; then
    if [ "$IS_ROOT" -eq 1 ]; then
      BINDIR=/usr/local/bin
    else
      BINDIR="${HOME}/.local/bin"
    fi
  fi
}

print_detect() {
  printf 'os_id=%s\n' "$OS_ID"
  printf 'os_version=%s\n' "$OS_VERSION"
  printf 'os_like=%s\n' "$OS_LIKE"
  printf 'python=%s\n' "${PYTHON:-}"
  printf 'python_version=%s\n' "${PYTHON_VERSION:-}"
  printf 'python_ok=%s\n' "$(py_meets "${PYTHON:-:}" && echo yes || echo no)"
  printf 'init=%s\n' "$INIT_SYS"
  printf 'root=%s\n' "$(is_root && echo yes || echo no)"
  printf 'prefix=%s\n' "$PREFIX"
  printf 'bindir=%s\n' "$BINDIR"
}

maybe_install_python_pkgs() {
  [ "$IS_ROOT" -eq 1 ] || return 0
  [ "$FORCE_USER" -eq 0 ] || return 0
  if py_meets "${PYTHON:-:}" && "$PYTHON" -c 'import venv, ensurepip' 2>/dev/null; then
    return 0
  fi
  log "installing Python venv packages"
  if have apt-get; then
    export DEBIAN_FRONTEND=noninteractive
    apt-get update -qq
    apt-get install -y -qq python3 python3-venv python3-pip ca-certificates tar gzip >/dev/null
  elif have dnf; then
    dnf install -y python3 python3-pip python3-virtualenv ca-certificates tar gzip >/dev/null
  elif have yum; then
    yum install -y python3 python3-pip ca-certificates tar gzip >/dev/null
  elif have apk; then
    apk add --no-cache python3 py3-pip ca-certificates tar gzip >/dev/null
  elif have zypper; then
    zypper --non-interactive install python3 python3-pip python3-virtualenv ca-certificates tar gzip >/dev/null
  else
    log "no supported package manager; will try existing python"
    return 0
  fi
  find_python || true
}

remote_version() {
  local ver
  ver=$(fetch_stdout "$BASE/downloads/VERSION" 2>/dev/null || true)
  ver=$(printf '%s' "$ver" | tr -d ' \t\r\n')
  if ! printf '%s' "$ver" | grep -Eq '^[0-9]+\.[0-9]+(\.[0-9]+)?$'; then
    ver=$VERSION_FALLBACK
  fi
  REMOTE_VERSION=$ver
}

install_venv() {
  local tarball expected actual work
  work=$(mktemp -d)
  tarball="$work/originreach-${REMOTE_VERSION}.tar.gz"
  log "downloading originreach ${REMOTE_VERSION}"
  fetch "$BASE/downloads/originreach-${REMOTE_VERSION}.tar.gz" "$tarball" || { rm -rf "$work"; return 1; }
  if fetch "$BASE/downloads/originreach-${REMOTE_VERSION}.tar.gz.sha256" "$work/sum" 2>/dev/null; then
    expected=$(awk '{print $1}' "$work/sum" | head -n1)
    actual=$(file_sha256 "$tarball")
    if [ -n "$expected" ] && [ -n "$actual" ] && [ "$expected" != "$actual" ]; then
      rm -rf "$work"
      die "SHA256 mismatch for originreach-${REMOTE_VERSION}.tar.gz"
    fi
  fi
  if [ -d "$PREFIX/venv" ]; then
    rm -rf "$PREFIX/venv"
  fi
  mkdir -p "$PREFIX"
  if ! "$PYTHON" -c 'import venv' 2>/dev/null; then
    rm -rf "$work"
    return 1
  fi
  if ! "$PYTHON" -m venv "$PREFIX/venv"; then
    rm -rf "$work"
    return 1
  fi
  if [ ! -x "$PREFIX/venv/bin/python" ]; then
    rm -rf "$work"
    return 1
  fi
  if [ -x "$PREFIX/venv/bin/pip" ]; then
    "$PREFIX/venv/bin/python" -m pip install --upgrade pip setuptools wheel >/dev/null || true
  fi
  if ! "$PREFIX/venv/bin/python" -m pip install "$tarball"; then
    rm -rf "$work" "$PREFIX/venv"
    return 1
  fi
  rm -rf "$work"
  [ -x "$PREFIX/venv/bin/originreach" ]
}

install_onefile() {
  local dest=$PREFIX/originreach-agent.py
  local src=$DEFAULT_URL/agent.py
  if [ -n "$DASH_URL" ]; then
    src=${DASH_URL%/}/agent.py
  fi
  mkdir -p "$PREFIX"
  log "Python ${PYTHON_VERSION:-unknown} < ${MIN_PY_MAJOR}.${MIN_PY_MINOR}; installing one-file agent"
  fetch "$src" "$dest"
  chmod 644 "$dest"
  [ -s "$dest" ]
}

write_wrapper() {
  mkdir -p "$PREFIX/bin" "$PREFIX/etc"
  cat > "$PREFIX/bin/originreach-agent-run" <<EOF
#!/bin/sh
set -e
PREFIX="$PREFIX"
if [ -f "\$PREFIX/etc/agent.env" ]; then
  set -a
  # shellcheck disable=SC1091
  . "\$PREFIX/etc/agent.env"
  set +a
fi
if [ -x "\$PREFIX/venv/bin/originreach" ]; then
  exec "\$PREFIX/venv/bin/originreach" agent "\$@"
fi
if [ -f "\$PREFIX/originreach-agent.py" ]; then
  exec "${PYTHON:-python3}" "\$PREFIX/originreach-agent.py" "\$@"
fi
echo "originreach agent is not installed" >&2
exit 1
EOF
  chmod 755 "$PREFIX/bin/originreach-agent-run"

  if [ "$INSTALL_MODE" = venv ]; then
    cat > "$PREFIX/bin/originreach" <<EOF
#!/bin/sh
exec "$PREFIX/venv/bin/originreach" "\$@"
EOF
  else
    cat > "$PREFIX/bin/originreach" <<EOF
#!/bin/sh
# One-file fallback: agent mode only.
exec "${PYTHON:-python3}" "$PREFIX/originreach-agent.py" "\$@"
EOF
  fi
  chmod 755 "$PREFIX/bin/originreach"
  mkdir -p "$BINDIR"
  prefix_bin=$(readlink -f "$PREFIX/bin" 2>/dev/null || echo "$PREFIX/bin")
  bindir_res=$(readlink -f "$BINDIR" 2>/dev/null || echo "$BINDIR")
  if [ "$prefix_bin" != "$bindir_res" ]; then
    ln -sfn "$PREFIX/bin/originreach" "$BINDIR/originreach"
  fi
}

write_agent_env() {
  [ "$TOKEN_SET" -eq 1 ] || return 0
  umask 077
  mkdir -p "$PREFIX/etc"
  cat > "$PREFIX/etc/agent.env" <<EOF
ORIGINREACH_URL=${DASH_URL:-$DEFAULT_URL}
ORIGINREACH_TOKEN=${TOKEN}
EOF
  chmod 600 "$PREFIX/etc/agent.env"
}

write_install_conf() {
  mkdir -p "$PREFIX/etc"
  cat > "$PREFIX/etc/install.conf" <<EOF
INSTALLED_VERSION=${REMOTE_VERSION}
INSTALL_MODE=${INSTALL_MODE}
PREFIX=${PREFIX}
BINDIR=${BINDIR}
SERVICE=${WANT_SERVICE:-0}
AUTO_UPDATE=${WANT_UPDATE:-0}
ORIGINREACH_URL=${DASH_URL:-}
ORIGINREACH_INSTALL_BASE=${BASE}
EOF
  chmod 644 "$PREFIX/etc/install.conf"
}

write_updater() {
  cat > "$PREFIX/bin/originreach-update" <<EOF
#!/bin/bash
set -euo pipefail
PREFIX="$PREFIX"
BASE="${BASE}"
CONF="\$PREFIX/etc/install.conf"
# shellcheck disable=SC1090
[ -f "\$CONF" ] && . "\$CONF"
if [ -f "\$PREFIX/etc/agent.env" ]; then
  # shellcheck disable=SC1091
  . "\$PREFIX/etc/agent.env"
fi
tmp=\$(mktemp)
trap 'rm -f "\$tmp"' EXIT
if command -v curl >/dev/null 2>&1; then
  curl -fsSL --retry 3 "\$BASE/install.sh" -o "\$tmp"
elif command -v wget >/dev/null 2>&1; then
  wget -q -O "\$tmp" "\$BASE/install.sh"
else
  echo "originreach-update: need curl or wget" >&2
  exit 1
fi
args=(--yes --prefix "\$PREFIX" --bindir "\${BINDIR:-$BINDIR}")
if [ "\${SERVICE:-0}" = 1 ]; then args+=(--service); else args+=(--no-service); fi
if [ "\${AUTO_UPDATE:-0}" = 1 ]; then args+=(--auto-update); else args+=(--no-auto-update); fi
if [ -n "\${ORIGINREACH_URL:-}" ]; then args+=(--url "\$ORIGINREACH_URL"); fi
if [ -n "\${ORIGINREACH_TOKEN:-}" ]; then args+=(--token "\$ORIGINREACH_TOKEN"); fi
if [ "\$(id -u)" -ne 0 ]; then args+=(--user); fi
bash "\$tmp" "\${args[@]}"
EOF
  chmod 755 "$PREFIX/bin/originreach-update"
}

ensure_system_user() {
  [ "$IS_ROOT" -eq 1 ] || return 1
  [ "${WANT_SERVICE:-0}" = 1 ] || return 1
  if id originreach >/dev/null 2>&1; then
    return 0
  fi
  if have useradd; then
    useradd --system --home-dir "$PREFIX" --no-create-home --shell /usr/sbin/nologin originreach 2>/dev/null \
      || useradd -r -d "$PREFIX" -s /sbin/nologin originreach 2>/dev/null \
      || return 1
    return 0
  fi
  if have adduser; then
    adduser -S -H -h "$PREFIX" -s /sbin/nologin originreach 2>/dev/null || return 1
    return 0
  fi
  return 1
}

install_systemd() {
  local unit dest user_flag=()
  if [ "$IS_ROOT" -eq 1 ]; then
    dest=/etc/systemd/system/originreach-agent.service
    unit=$(cat <<EOF
[Unit]
Description=OriginReach agent
After=network.target
Documentation=https://originreach.tacticaldataconcepts.com/install

[Service]
Type=simple
User=SVCUSER
EnvironmentFile=-$PREFIX/etc/agent.env
ExecStart=$PREFIX/bin/originreach-agent-run
Restart=always
RestartSec=10
WorkingDirectory=$PREFIX

[Install]
WantedBy=multi-user.target
EOF
)
    if ensure_system_user; then
      unit=${unit/SVCUSER/originreach}
      chown -R originreach:originreach "$PREFIX" 2>/dev/null || true
      chmod 750 "$PREFIX/etc"
      [ -f "$PREFIX/etc/agent.env" ] && chmod 640 "$PREFIX/etc/agent.env"
    else
      unit=${unit/User=SVCUSER/}
    fi
    printf '%s\n' "$unit" > "$dest"
    systemctl daemon-reload
    if [ "$TOKEN_SET" -eq 1 ]; then
      systemctl enable --now originreach-agent.service
    else
      systemctl enable originreach-agent.service
      log "service installed; add $PREFIX/etc/agent.env then: systemctl start originreach-agent"
    fi
  else
    dest="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/originreach-agent.service"
    mkdir -p "$(dirname "$dest")"
    cat > "$dest" <<EOF
[Unit]
Description=OriginReach agent
After=network.target

[Service]
Type=simple
EnvironmentFile=-$PREFIX/etc/agent.env
ExecStart=$PREFIX/bin/originreach-agent-run
Restart=always
RestartSec=10
WorkingDirectory=$PREFIX

[Install]
WantedBy=default.target
EOF
    systemctl --user daemon-reload
    if [ "$TOKEN_SET" -eq 1 ]; then
      systemctl --user enable --now originreach-agent.service
    else
      systemctl --user enable originreach-agent.service
    fi
    if have loginctl; then
      loginctl enable-linger "$USER" 2>/dev/null || true
    fi
  fi
}

install_openrc() {
  [ "$IS_ROOT" -eq 1 ] || return 1
  cat > /etc/init.d/originreach-agent <<EOF
#!/sbin/openrc-run
name="originreach-agent"
command="$PREFIX/bin/originreach-agent-run"
command_background=true
pidfile="/run/originreach-agent.pid"

depend() {
  need net
}
EOF
  chmod 755 /etc/init.d/originreach-agent
  rc-update add originreach-agent default 2>/dev/null || true
  if [ "$TOKEN_SET" -eq 1 ]; then
    rc-service originreach-agent start 2>/dev/null || /etc/init.d/originreach-agent start || true
  fi
}

install_cron_agent() {
  local line="* * * * * $PREFIX/bin/originreach-agent-watch"
  cat > "$PREFIX/bin/originreach-agent-watch" <<EOF
#!/bin/sh
if command -v pgrep >/dev/null 2>&1; then
  pgrep -f "$PREFIX/bin/originreach-agent-run" >/dev/null 2>&1 && exit 0
fi
nohup "$PREFIX/bin/originreach-agent-run" >>"$PREFIX/agent.log" 2>&1 &
EOF
  chmod 755 "$PREFIX/bin/originreach-agent-watch"
  if [ "$IS_ROOT" -eq 1 ] && [ -d /etc/cron.d ]; then
    printf '%s\n' "$line" | sed "s#^\*#*#" > /etc/cron.d/originreach-agent
    # root crontab style
    printf '* * * * * root %s\n' "$PREFIX/bin/originreach-agent-watch" > /etc/cron.d/originreach-agent
    chmod 644 /etc/cron.d/originreach-agent
  elif have crontab; then
    local tmp
    tmp=$(mktemp)
    crontab -l 2>/dev/null | grep -v originreach-agent-watch > "$tmp" || true
    printf '%s\n' "$line" >> "$tmp"
    crontab "$tmp"
    rm -f "$tmp"
  else
    log "no cron available; start the agent manually: $PREFIX/bin/originreach-agent-run"
    return 1
  fi
  if [ "$TOKEN_SET" -eq 1 ]; then
    "$PREFIX/bin/originreach-agent-watch" || true
  fi
}

install_service() {
  [ "${WANT_SERVICE:-0}" = 1 ] || return 0
  case "$INIT_SYS" in
    systemd) install_systemd ;;
    openrc) install_openrc || install_cron_agent ;;
    cron) install_cron_agent ;;
    *)
      log "no supported service manager; using cron if possible"
      install_cron_agent || true
      ;;
  esac
}

install_auto_update() {
  [ "${WANT_UPDATE:-0}" = 1 ] || return 0
  write_updater
  if [ "$INIT_SYS" = systemd ]; then
    if [ "$IS_ROOT" -eq 1 ]; then
      cat > /etc/systemd/system/originreach-update.service <<EOF
[Unit]
Description=OriginReach auto-update
After=network.target

[Service]
Type=oneshot
ExecStart=$PREFIX/bin/originreach-update
EOF
      cat > /etc/systemd/system/originreach-update.timer <<EOF
[Unit]
Description=OriginReach daily update

[Timer]
OnCalendar=daily
Persistent=true
RandomizedDelaySec=3600

[Install]
WantedBy=timers.target
EOF
      systemctl daemon-reload
      systemctl enable --now originreach-update.timer
    else
      local ud="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"
      mkdir -p "$ud"
      cat > "$ud/originreach-update.service" <<EOF
[Unit]
Description=OriginReach auto-update

[Service]
Type=oneshot
ExecStart=$PREFIX/bin/originreach-update
EOF
      cat > "$ud/originreach-update.timer" <<EOF
[Unit]
Description=OriginReach daily update

[Timer]
OnCalendar=daily
Persistent=true
RandomizedDelaySec=3600

[Install]
WantedBy=timers.target
EOF
      systemctl --user daemon-reload
      systemctl --user enable --now originreach-update.timer
    fi
  elif [ "$IS_ROOT" -eq 1 ] && [ -d /etc/cron.d ]; then
    printf '15 4 * * * root %s\n' "$PREFIX/bin/originreach-update" > /etc/cron.d/originreach-update
    chmod 644 /etc/cron.d/originreach-update
  elif have crontab; then
    local tmp
    tmp=$(mktemp)
    crontab -l 2>/dev/null | grep -v originreach-update > "$tmp" || true
    printf '15 4 * * * %s\n' "$PREFIX/bin/originreach-update" >> "$tmp"
    crontab "$tmp"
    rm -f "$tmp"
  else
    log "could not schedule auto-update; run $PREFIX/bin/originreach-update yourself"
  fi
}

prompt_options() {
  if [ -z "$WANT_SERVICE" ]; then
    if ask_yn "Run the OriginReach agent as a ${INIT_SYS} service? [y/N] " N; then
      WANT_SERVICE=1
    else
      WANT_SERVICE=0
    fi
  fi
  if [ -z "$WANT_UPDATE" ]; then
    if ask_yn "Enable automatic updates (daily, default yes)? [Y/n] " Y; then
      WANT_UPDATE=1
    else
      WANT_UPDATE=0
    fi
  fi
}

print_usage_banner() {
  local path_note=""
  case ":$PATH:" in
    *":$BINDIR:"*) ;;
    *) path_note="Add $BINDIR to PATH, then re-open the shell." ;;
  esac
  cat <<EOF

OriginReach ${REMOTE_VERSION} installed (${INSTALL_MODE}).

CLI (no account needed):
  originreach check --origin http://192.168.1.50:8080/ --public https://app.example.com/
  originreach check -i inventory.json --exit-code
  originreach watch -i inventory.json --interval 30

Enroll this host with the hosted dashboard:
  originreach agent --url ${DASH_URL:-$DEFAULT_URL} --token orva_YOUR_TOKEN

Or install + enroll in one step:
  curl -fsSL ${DEFAULT_BASE}/install.sh | sudo bash -s -- --token orva_YOUR_TOKEN

Service: $([ "${WANT_SERVICE:-0}" = 1 ] && echo "yes (${INIT_SYS})" || echo "no")
Auto-update: $([ "${WANT_UPDATE:-0}" = 1 ] && echo "yes (daily)" || echo "no")
Prefix: ${PREFIX}
${path_note}
EOF
  if [ "$TOKEN_SET" -eq 1 ]; then
    printf 'Agent enrolled against %s\n' "${DASH_URL:-$DEFAULT_URL}"
  fi
  if [ "$INSTALL_MODE" = onefile ]; then
    printf '\nNote: this host has Python %s; only agent mode is available.\n' "${PYTHON_VERSION:-unknown}"
    printf 'Install Python 3.10+ for the full CLI (check / watch).\n'
  fi
}

main() {
  parse_args "$@"
  read_os
  detect_init
  find_python || true
  set_defaults
  if [ "$DETECT_ONLY" -eq 1 ]; then
    print_detect
    exit 0
  fi
  if ! have curl && ! have wget; then
    die "need curl or wget to download OriginReach"
  fi
  if ! have tar; then
    die "need tar"
  fi
  prompt_options
  maybe_install_python_pkgs
  find_python || true
  remote_version
  mkdir -p "$PREFIX/bin" "$PREFIX/etc"
  if py_meets "${PYTHON:-:}"; then
    if install_venv; then
      INSTALL_MODE=venv
    else
      log "venv install failed; falling back to one-file agent"
      install_onefile || die "could not install OriginReach"
      INSTALL_MODE=onefile
    fi
  else
    install_onefile || die "could not install OriginReach (need Python 3.10+ or agent.py)"
    INSTALL_MODE=onefile
  fi
  write_wrapper
  write_agent_env
  write_install_conf
  install_service
  install_auto_update
  print_usage_banner
}

main "$@"
