#!/usr/bin/env bash
# user_data.sh — runs on first boot of the VM via Terraform's `user_data` arg.
# Installs Docker, drops the compose + Caddy files into /srv/url-shortener/,
# writes a starter .env, then brings the stack up.
# Reader-facing copy: cloud-devops/lesson08-terraform-basics/lab_guide.html.
#
# NOTE: The <<'COMPOSE'> and <<'CADDY' heredocs below are STUBS.
# Lab 08 Step 4 walks you through filling them in (Option A: inline the file
# contents; Option B: curl from GitHub raw; Option C: scp post-boot).

set -euxo pipefail
exec > >(tee /var/log/url-shortener-bootstrap.log) 2>&1

apt-get update
apt-get install -y ca-certificates curl
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
  -o /etc/apt/keyrings/docker.asc
chmod a+r /etc/apt/keyrings/docker.asc
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] \
  https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo $VERSION_CODENAME) stable" \
  > /etc/apt/sources.list.d/docker.list
apt-get update
apt-get install -y docker-ce docker-ce-cli containerd.io \
  docker-buildx-plugin docker-compose-plugin

mkdir -p /srv/url-shortener/caddy

# STUB: replace with the full contents of cloud-devops/sample-app/docker-compose.prod.yml
# See Lab 08 Step 4 for the three fill-in options.
cat > /srv/url-shortener/docker-compose.prod.yml <<'COMPOSE'
# TODO: paste docker-compose.prod.yml contents here (Lab 08 Step 4, Option A)
# or use: curl -fsSL <github-raw-url> > /srv/url-shortener/docker-compose.prod.yml
COMPOSE

# STUB: replace with the full contents of cloud-devops/sample-app/caddy/Caddyfile
cat > /srv/url-shortener/caddy/Caddyfile <<'CADDY'
# TODO: paste Caddyfile contents here (Lab 08 Step 4, Option A)
# or use: curl -fsSL <github-raw-url> > /srv/url-shortener/caddy/Caddyfile
CADDY

cat > /srv/url-shortener/.env <<EOF
GHCR_OWNER=${ghcr_owner}
DOMAIN=${domain}
ACME_EMAIL=${acme_email}
DB_PASSWORD=$(openssl rand -hex 16)
SECRET_KEY=$(openssl rand -hex 32)
WORKER_INTERVAL=60
EOF
chmod 600 /srv/url-shortener/.env

cd /srv/url-shortener
docker compose -f docker-compose.prod.yml pull
docker compose -f docker-compose.prod.yml up -d
