#!/usr/bin/env bash
#
# tmuxapp installer (Debian/Ubuntu)
#
#   curl -fsSL https://tmuxapp.com/install.sh | bash
#
# Installs system deps (tmux/git), Bun, the app, and a systemd service that runs
# it as the current user. Configure via env vars:
#
#   TMUXAPP_REPO   git URL to clone            (optional; default downloads a tarball)
#   TMUXAPP_TARBALL  app tarball URL           (default: https://tmuxapp.com/tmuxapp.tar.gz)
#   TMUXAPP_REF    branch/tag to check out     (default: main; only with TMUXAPP_REPO)
#   INSTALL_DIR    where to install            (default: /opt/tmuxapp)
#   PORT           port to listen on           (default: 33333)
#   HOST_BIND      bind address                (default: 0.0.0.0; set 127.0.0.1 for local-only)
#   INSTALL_SERVICE  set to 0 to skip systemd  (default: 1)
#
# Example:
#   curl -fsSL https://tmuxapp.com/install.sh | TMUXAPP_REPO=https://github.com/you/tmuxapp.git bash
#
set -euo pipefail

INSTALL_DIR="${INSTALL_DIR:-/opt/tmuxapp}"
PORT="${PORT:-33333}"
HOST_BIND="${HOST_BIND:-0.0.0.0}"
TMUXAPP_REPO="${TMUXAPP_REPO:-https://github.com/REPLACE-ME/tmuxapp.git}"
TMUXAPP_REF="${TMUXAPP_REF:-main}"
TMUXAPP_TARBALL="${TMUXAPP_TARBALL:-https://tmuxapp.com/tmuxapp.tar.gz}"
SERVICE_NAME="${SERVICE_NAME:-tmuxapp}"
INSTALL_SERVICE="${INSTALL_SERVICE:-1}"
RUN_USER="$(id -un)"
USER_HOME="$(getent passwd "$RUN_USER" | cut -d: -f6)"
USER_HOME="${USER_HOME:-$HOME}"

c_step() { printf '\033[1;35m▸\033[0m %s\n' "$*"; }
c_warn() { printf '\033[1;33m!\033[0m %s\n' "$*"; }
c_err()  { printf '\033[1;31m✗\033[0m %s\n' "$*" >&2; }

# Run a command as root (via sudo if we aren't already root).
as_root() {
  if [ "$(id -u)" -eq 0 ]; then "$@"; else sudo "$@"; fi
}

if [ "$(id -u)" -ne 0 ] && ! command -v sudo >/dev/null 2>&1; then
  c_err "This installer needs root or sudo (for apt + systemd)."
  exit 1
fi

# ── 1. System packages ────────────────────────────────────────────────────────
if command -v apt-get >/dev/null 2>&1; then
  c_step "Installing system packages (tmux, git, curl, unzip)…"
  as_root apt-get update -y
  as_root apt-get install -y --no-install-recommends tmux git curl unzip ca-certificates
else
  c_warn "Not a Debian/apt system — ensure tmux, git, curl, unzip are installed."
fi

# ── 2. Bun ────────────────────────────────────────────────────────────────────
BUN="$(command -v bun || true)"
if [ -z "$BUN" ] && [ -x "$USER_HOME/.bun/bin/bun" ]; then BUN="$USER_HOME/.bun/bin/bun"; fi
if [ -z "$BUN" ]; then
  c_step "Installing Bun…"
  curl -fsSL https://bun.sh/install | bash
  BUN="$USER_HOME/.bun/bin/bun"
fi
c_step "Bun: $("$BUN" --version) ($BUN)"

# ── 3. Fetch the app ──────────────────────────────────────────────────────────
as_root mkdir -p "$INSTALL_DIR"
as_root chown "$RUN_USER:$(id -gn "$RUN_USER")" "$INSTALL_DIR"

if [ -d "$INSTALL_DIR/.git" ]; then
  c_step "Updating existing checkout in $INSTALL_DIR…"
  git -C "$INSTALL_DIR" fetch --depth 1 origin "$TMUXAPP_REF"
  git -C "$INSTALL_DIR" checkout -f "$TMUXAPP_REF"
  git -C "$INSTALL_DIR" reset --hard "origin/$TMUXAPP_REF" 2>/dev/null || true
elif [ -f "$INSTALL_DIR/package.json" ]; then
  c_step "Using existing files in $INSTALL_DIR (no git)…"
elif [ "$TMUXAPP_REPO" != "https://github.com/REPLACE-ME/tmuxapp.git" ]; then
  c_step "Cloning $TMUXAPP_REPO@$TMUXAPP_REF → $INSTALL_DIR…"
  git clone --depth 1 --branch "$TMUXAPP_REF" "$TMUXAPP_REPO" "$INSTALL_DIR"
else
  c_step "Downloading app from $TMUXAPP_TARBALL …"
  curl -fsSL "$TMUXAPP_TARBALL" | tar -xz -C "$INSTALL_DIR"
fi

# ── 4. Dependencies ───────────────────────────────────────────────────────────
c_step "Installing dependencies…"
( cd "$INSTALL_DIR" && "$BUN" install --frozen-lockfile )

# ── 5. Config (.env) ──────────────────────────────────────────────────────────
ENV_FILE="$INSTALL_DIR/.env"
if [ ! -f "$ENV_FILE" ]; then
  # Password precedence: $APP_PASSWORD env → interactive prompt (/dev/tty, since
  # stdin is the piped script under `curl | bash`) → random.
  PW=""
  PW_SOURCE="generated"
  if [ -n "${APP_PASSWORD:-}" ]; then
    PW="$APP_PASSWORD"
    PW_SOURCE="provided"
  elif [ -r /dev/tty ]; then
    printf 'Choose a panel password (Enter for a random one): ' > /dev/tty
    read -rs PW < /dev/tty || PW=""
    printf '\n' > /dev/tty
    [ -n "$PW" ] && PW_SOURCE="chosen"
  fi
  [ -z "$PW" ] && PW="$(head -c 24 /dev/urandom | base64 | tr -dc 'A-Za-z0-9' | head -c 24)"

  c_step "Writing $ENV_FILE …"
  cat > "$ENV_FILE" <<EOF
APP_PASSWORD=$PW
HOST=$HOST_BIND
PORT=$PORT
DATABASE_URL=$INSTALL_DIR/lifeweb.db
SESSION_COMMAND=claude
# Safer default for a networked server. Use bypassPermissions for full tool access.
CHAT_PERMISSION_MODE=dontAsk
EOF
  [ "$PW_SOURCE" = "generated" ] && GENERATED_PW="$PW"
else
  c_warn "$ENV_FILE already exists — leaving it unchanged."
fi

# ── 6. Claude Code check ──────────────────────────────────────────────────────
if ! command -v claude >/dev/null 2>&1 && [ ! -x "$USER_HOME/.local/bin/claude" ]; then
  c_warn "Claude Code ('claude') not found. Install it and run 'claude' once to"
  c_warn "authenticate AS THIS USER ($RUN_USER) before sessions will work."
fi

# ── 7. systemd service ────────────────────────────────────────────────────────
if [ "$INSTALL_SERVICE" = "1" ]; then
  c_step "Installing systemd service '$SERVICE_NAME'…"
  UNIT="/etc/systemd/system/$SERVICE_NAME.service"
  as_root tee "$UNIT" >/dev/null <<EOF
[Unit]
Description=tmuxapp — web control panel for tmux-hosted Claude
After=network.target

[Service]
Type=simple
User=$RUN_USER
WorkingDirectory=$INSTALL_DIR
# Include the user's bun + ~/.local/bin (claude) on PATH so spawned tmux/claude resolve.
Environment=PATH=$USER_HOME/.bun/bin:$USER_HOME/.local/bin:/usr/local/bin:/usr/bin:/bin
Environment=NODE_ENV=production
ExecStart=$BUN run start
Restart=on-failure
RestartSec=2

[Install]
WantedBy=multi-user.target
EOF
  as_root systemctl daemon-reload
  as_root systemctl enable --now "$SERVICE_NAME"
  sleep 1
  as_root systemctl --no-pager --lines=0 status "$SERVICE_NAME" || true
fi

# ── Summary ───────────────────────────────────────────────────────────────────
echo
c_step "Done. tmuxapp is installed at $INSTALL_DIR"
echo   "    Listening on http://$HOST_BIND:$PORT"
[ -n "${GENERATED_PW:-}" ] && echo "    Password (APP_PASSWORD): $GENERATED_PW  (saved in .env)"
echo
echo "  Next:"
echo "   • Authenticate Claude as $RUN_USER:   claude"
echo "   • Logs:                                journalctl -u $SERVICE_NAME -f"
echo "   • Restart after config changes:        sudo systemctl restart $SERVICE_NAME"
echo "   • Put it behind TLS for tmuxapp.com (Caddy):"
echo "         tmuxapp.com { reverse_proxy $HOST_BIND:$PORT }"
echo
c_warn "Bound to ${HOST_BIND}:${PORT} — reachable from the network. This panel runs"
c_warn "arbitrary commands, and plain HTTP sends the password in the clear. Strongly"
c_warn "recommended: a TLS reverse proxy (Caddy), a firewall/IP allowlist, and a strong"
c_warn "password. To keep it local-only instead, set HOST=127.0.0.1 in $ENV_FILE."
