#!/usr/bin/env bash
# In-House AI installer
# Repo: https://github.com/razajahangir/inhouse-ai
# Inspect this file before piping it to bash.
#
# Non-interactive use: set INHOUSE_ACCESS (cloudflare|tailscale|local) and
# INHOUSE_RUNTIME (ollama|vllm). Optional: INHOUSE_DIR, INHOUSE_BRANCH,
# CLOUDFLARE_TUNNEL_TOKEN, TS_AUTHKEY, TS_HOSTNAME, VLLM_MODEL.

set -euo pipefail

REPO="${INHOUSE_REPO:-https://github.com/razajahangir/inhouse-ai.git}"
DIR="${INHOUSE_DIR:-$HOME/in-house-ai}"
BRANCH="${INHOUSE_BRANCH:-main}"

if [[ -t 1 ]]; then
  BOLD=$'\033[1m'
  DIM=$'\033[2m'
  RESET=$'\033[0m'
else
  BOLD="" DIM="" RESET=""
fi

say() { printf '%s\n' "$*"; }
fail() { printf 'error: %s\n' "$*" >&2; exit 1; }

need() {
  command -v "$1" >/dev/null 2>&1 || fail "missing dependency: $1"
}

ask() {
  local prompt="$1" default="${2:-}" answer=""
  # /dev/tty can look readable yet fail to open (no controlling terminal), so test it.
  if ! { true < /dev/tty; } 2>/dev/null; then
    printf '%s' "$default"
    return
  fi
  if [[ -n "$default" ]]; then
    printf '%s [%s]: ' "$prompt" "$default" > /dev/tty
  else
    printf '%s: ' "$prompt" > /dev/tty
  fi
  IFS= read -r answer < /dev/tty || true
  if [[ -z "$answer" ]]; then
    answer="$default"
  fi
  printf '%s' "$answer"
}

set_kv() {
  local key="$1" value="$2" tmp
  tmp="$(mktemp)"
  if [[ -f .env ]] && grep -q "^${key}=" .env; then
    while IFS= read -r line || [[ -n "$line" ]]; do
      if [[ "$line" == "${key}="* ]]; then
        printf '%s=%s\n' "$key" "$value"
      else
        printf '%s\n' "$line"
      fi
    done < .env > "$tmp"
    mv "$tmp" .env
  else
    rm -f "$tmp"
    printf '%s=%s\n' "$key" "$value" >> .env
  fi
}

say ""
say "${BOLD}In-House AI${RESET}"
say "Private chat, local models, RAG on your own machine."
say ""

need git
need openssl
need docker

if ! docker compose version >/dev/null 2>&1; then
  fail "Docker Compose v2 is required (docker compose)."
fi

if ! docker info >/dev/null 2>&1; then
  fail "Docker is installed but not running, or this user cannot talk to the daemon."
fi

if [[ -d "$DIR/.git" ]]; then
  say "Using existing checkout at ${DIR}"
  git -C "$DIR" fetch --quiet origin "$BRANCH" || true
  git -C "$DIR" checkout --quiet "$BRANCH"
  git -C "$DIR" pull --ff-only --quiet origin "$BRANCH" || say "${DIM}Could not fast-forward; leaving the working tree as-is.${RESET}"
else
  if [[ -e "$DIR" ]]; then
    fail "$DIR exists and is not a git checkout. Set INHOUSE_DIR to another path."
  fi
  say "Cloning into ${DIR}"
  git clone --branch "$BRANCH" --depth 1 "$REPO" "$DIR"
fi

cd "$DIR"

ACCESS="${INHOUSE_ACCESS:-}"
RUNTIME="${INHOUSE_RUNTIME:-}"

if [[ -z "$ACCESS" ]]; then
  say ""
  say "How will you reach it?"
  say "  1) Cloudflare Tunnel   — public hostname, login protected by Cloudflare Access"
  say "  2) Tailscale           — private, end-to-end encrypted"
  say "  3) Local only          — this machine, http://127.0.0.1:3000"
  choice="$(ask "Choose 1/2/3" "3")"
  case "$choice" in
    1|cloudflare|Cloudflare) ACCESS="cloudflare" ;;
    2|tailscale|Tailscale) ACCESS="tailscale" ;;
    *) ACCESS="local" ;;
  esac
fi

if [[ -z "$RUNTIME" ]]; then
  say ""
  say "Model server"
  say "  1) Ollama   — laptops and small GPUs, the default"
  say "  2) vLLM     — larger GPUs, more concurrent users (NVIDIA)"
  choice="$(ask "Choose 1/2" "1")"
  case "$choice" in
    2|vllm|vLLM) RUNTIME="vllm" ;;
    *) RUNTIME="ollama" ;;
  esac
fi

if [[ ! -f .env ]]; then
  if [[ ! -f .env.example ]]; then
    fail "No .env.example in the checkout."
  fi
  cp .env.example .env
  set_kv WEBUI_SECRET_KEY "$(openssl rand -hex 32)"
  set_kv POSTGRES_PASSWORD "$(openssl rand -hex 32)"
  set_kv LITELLM_MASTER_KEY "sk-$(openssl rand -hex 32)"
  say ""
  say "Wrote ${DIR}/.env with fresh secrets. Values are not printed."
else
  say ""
  say "Keeping existing ${DIR}/.env"
fi

PROFILES=""
case "$ACCESS" in
  cloudflare) PROFILES="cloudflare" ;;
  tailscale)  PROFILES="tailscale" ;;
esac
if [[ "$RUNTIME" == "vllm" ]]; then
  PROFILES="${PROFILES:+$PROFILES,}vllm"
fi
# Compose reads COMPOSE_PROFILES from .env. An empty value starts the core stack only.
set_kv COMPOSE_PROFILES "$PROFILES"

if [[ "$ACCESS" == "cloudflare" ]]; then
  say ""
  say "Cloudflare: Zero Trust → Networks → Tunnels → create a tunnel (Docker)."
  say "Copy only the token (it starts with eyJ). Do not run the docker command it shows."
  say "Public hostname service: HTTP, open-webui:8080"
  token="${CLOUDFLARE_TUNNEL_TOKEN:-$(ask "CLOUDFLARE_TUNNEL_TOKEN (blank to fill later)")}"
  if [[ -n "$token" ]]; then
    set_kv CLOUDFLARE_TUNNEL_TOKEN "$token"
  fi
fi

if [[ "$ACCESS" == "tailscale" ]]; then
  say ""
  say "Tailscale: admin console → Settings → Keys → generate an auth key."
  say "HTTPS must be enabled for your tailnet (admin console → DNS → HTTPS Certificates)."
  key="${TS_AUTHKEY:-$(ask "TS_AUTHKEY (blank to fill later)")}"
  if [[ -n "$key" ]]; then
    set_kv TS_AUTHKEY "$key"
  fi
  host="${TS_HOSTNAME:-$(ask "Tailscale device name" "in-house-ai")}"
  set_kv TS_HOSTNAME "$host"
fi

if [[ "$RUNTIME" == "vllm" ]]; then
  vmodel="${VLLM_MODEL:-$(ask "Hugging Face model for vLLM" "Qwen/Qwen2.5-0.5B-Instruct")}"
  set_kv VLLM_MODEL "$vmodel"
  # Point the chat model at vLLM. Embeddings stay on Ollama.
  tmp="$(mktemp)"
  awk '
    /model_name: local-chat/  { in_chat = 1 }
    /model_name: local-embed/ { in_chat = 0 }
    in_chat && /^[[:space:]]*model:/    { sub(/model:.*/, "model: hosted_vllm/local-chat") }
    in_chat && /^[[:space:]]*api_base:/ { sub(/api_base:.*/, "api_base: http://vllm:8000/v1") }
    { print }
  ' litellm/config.yaml > "$tmp" && mv "$tmp" litellm/config.yaml
  say ""
  say "Updated litellm/config.yaml: local-chat now uses vLLM. Embeddings stay on Ollama."
  if ! command -v nvidia-smi >/dev/null 2>&1; then
    say "${DIM}Warning: nvidia-smi not found. vLLM needs an NVIDIA GPU and the NVIDIA Container Toolkit.${RESET}"
  fi
elif ! command -v nvidia-smi >/dev/null 2>&1; then
  say ""
  say "${DIM}No NVIDIA GPU found. The ollama service reserves one by default; if it fails to start,"
  say "remove its deploy: block in docker-compose.yaml and run this again.${RESET}"
fi

say ""
say "Starting the stack. The first run downloads about 3 GB of models."
docker compose up -d

say ""
say "${BOLD}Where things are${RESET}"
say "  Open WebUI   http://127.0.0.1:3000  (this machine only)"
if [[ "$ACCESS" == "cloudflare" ]]; then
  say "               https://<your-hostname>  once the tunnel route points at http://open-webui:8080"
  say "               and a Cloudflare Access policy protects it"
fi
if [[ "$ACCESS" == "tailscale" ]]; then
  say "               https://${host:-in-house-ai}.<your-tailnet>.ts.net  (devices on your tailnet)"
fi
say "  LiteLLM      not published outside Docker. Inside the network: http://litellm:4000"
say "               Its admin UI is off the network by default. To open it on this machine,"
say "               add to the litellm service in docker-compose.yaml:"
say "                 ports: [\"127.0.0.1:4000:4000\"]"
say "               run: docker compose up -d   then open http://127.0.0.1:4000/ui"
say "               Login: admin / the LITELLM_MASTER_KEY value in ${DIR}/.env"
say "  Test API     docker compose exec open-webui curl -s http://litellm:4000/v1/models \\"
say "                 -H \"Authorization: Bearer \$(grep '^LITELLM_MASTER_KEY=' .env | cut -d= -f2)\""

say ""
say "${BOLD}Next${RESET}"
say "  1. Models are downloading: docker compose logs -f ollama-init"
say "  2. Open the Open WebUI address above and create the first account. It becomes the admin."
say "  3. Then set ENABLE_SIGNUP to \"false\" in docker-compose.yaml and run: docker compose up -d"

if [[ "$ACCESS" == "cloudflare" ]] && grep -q '^CLOUDFLARE_TUNNEL_TOKEN=replace' .env; then
  say ""
  say "${BOLD}Action needed${RESET}: no Cloudflare token yet. Put it in ${DIR}/.env, then run:"
  say "  docker compose up -d --force-recreate cloudflared"
fi
if [[ "$ACCESS" == "tailscale" ]] && grep -q '^TS_AUTHKEY=replace' .env; then
  say ""
  say "${BOLD}Action needed${RESET}: no Tailscale auth key yet. Put it in ${DIR}/.env, then run:"
  say "  docker compose up -d --force-recreate tailscale"
fi
if [[ "$RUNTIME" == "vllm" ]]; then
  say ""
  say "vLLM: chat runs on vLLM (${vmodel}); embeddings stay on Ollama. Check: docker compose logs -f vllm"
fi
say ""
say "More: docker compose ps · docker compose logs -f · Checkout: ${DIR}"
