#!/bin/bash
# One-time EC2 setup. Run as root on a fresh Ubuntu 22.04/24.04 instance:
#   sudo bash deploy/setup-ec2.sh
#
# Installs Node 22, creates an unprivileged service user, installs the app to
# /opt/chatgpt-chatbot, and wires up systemd. It does NOT write the .env file —
# that is the one step left manual, so the OpenAI key never passes through a
# script, your shell history, or this repo.
set -euo pipefail

APP_DIR=/opt/chatgpt-chatbot
ENV_FILE=/etc/chatgpt-chatbot.env
SERVICE_USER=chatbot

if [ "$EUID" -ne 0 ]; then
  echo "Run as root: sudo bash deploy/setup-ec2.sh" >&2
  exit 1
fi

echo "==> Installing Node.js 22"
if ! command -v node >/dev/null 2>&1 || [ "$(node -v | cut -d. -f1 | tr -d v)" -lt 20 ]; then
  curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
  apt-get install -y nodejs
fi
node -v

echo "==> Creating service user '$SERVICE_USER'"
id -u "$SERVICE_USER" >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin "$SERVICE_USER"

echo "==> Installing application to $APP_DIR"
mkdir -p "$APP_DIR"
# Run this from the repo root so the copy picks up the checked-out code.
cp -r package.json package-lock.json src public "$APP_DIR"/
cd "$APP_DIR"
npm ci --omit=dev

# The app only ever reads its own files. Owned by root, readable by the service
# user, so a compromise of the process cannot rewrite the code it runs.
chown -R root:"$SERVICE_USER" "$APP_DIR"
chmod -R 750 "$APP_DIR"

echo "==> Preparing $ENV_FILE"
if [ ! -f "$ENV_FILE" ]; then
  install -m 600 -o root -g "$SERVICE_USER" /dev/null "$ENV_FILE"
  cat > "$ENV_FILE" <<'TEMPLATE'
OPENAI_API_KEY=
OPENAI_MODEL=gpt-4o-mini
API_KEYS=
ALLOWED_ORIGINS=
PORT=3000
NODE_ENV=production
TRUST_PROXY=true
RATE_LIMIT_MAX=20
RATE_LIMIT_WINDOW_SECONDS=60
DAILY_LIMIT_MAX=200
MAX_MESSAGE_CHARS=4000
MAX_OUTPUT_TOKENS=4000
CONVERSATION_TTL_HOURS=24
TEMPLATE
  chmod 640 "$ENV_FILE"
  chown root:"$SERVICE_USER" "$ENV_FILE"
  echo "    created — fill in OPENAI_API_KEY and API_KEYS before starting"
else
  echo "    already exists, left untouched"
fi

echo "==> Installing systemd unit"
cp "$(dirname "$0")/chatgpt-chatbot.service" /etc/systemd/system/
systemctl daemon-reload
systemctl enable chatgpt-chatbot

cat <<DONE

Setup complete. Remaining steps:

  1. Generate an API key for your clients:
       openssl rand -base64 32
  2. Edit $ENV_FILE and set OPENAI_API_KEY and API_KEYS.
     The server refuses to start if either is missing.
  3. systemctl start chatgpt-chatbot
     journalctl -u chatgpt-chatbot -f
  4. curl localhost:3000/health

Do not open port 3000 in the security group. Put nginx in front (see
deploy/nginx.conf) and allow only 80/443 from the internet.
DONE
