#!/bin/sh
# Alan-a-Dale setup: writes docker-compose.yml, .env.example and .env into the current
# directory, pulls the newest image and starts the server. Run it again to update.
#   ALAN_VERSION=0.1.0rc52 sh install.sh    pin a version (default: newest)
#   ALAN_NO_START=1 sh install.sh           only write the files
set -eu

REGISTRY="${ALAN_REGISTRY:-git.capjoy.dev}"
REPO="${ALAN_REPO:-andre-capjoy/alan-a-dale}"
IMAGE="$REGISTRY/$REPO"

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

command -v docker >/dev/null 2>&1 || die "docker is not installed"
docker compose version >/dev/null 2>&1 || die "the docker compose plugin is not installed"

newest_tag() {
  command -v curl >/dev/null 2>&1 || return 0
  token=$(curl -fsSL "https://$REGISTRY/v2/token?service=container_registry&scope=repository:$REPO:pull" |
    sed -n 's/.*"token":"\([^"]*\)".*/\1/p') || return 0
  [ -n "$token" ] || return 0
  curl -fsSL -H "Authorization: Bearer $token" "https://$REGISTRY/v2/$REPO/tags/list" |
    tr ',[]' '\n\n\n' | sed -n 's/.*"\([0-9][^"]*\)".*/\1/p' |
    sed 's/rc/~rc/' | sort -V | sed 's/~rc/rc/' | tail -n 1
}

version="${ALAN_VERSION:-}"
[ -n "$version" ] || version=$(newest_tag || true)
[ -n "$version" ] || version=latest
say "Alan-a-Dale $version"

cat > docker-compose.yml <<YML
# Alan-a-Dale. Settings are read from .env (see .env.example).
services:
  alan-a-dale:
    image: \${ALAN_IMAGE:-$IMAGE:$version}
    restart: unless-stopped
    ports:
      - "\${ALAN_PORT:-8000}:8000"
    environment:
      PUID: \${PUID:-0}
      PGID: \${PGID:-0}
      ALAN_GIT_NAME: \${ALAN_GIT_NAME:-}
      ALAN_GIT_EMAIL: \${ALAN_GIT_EMAIL:-}
    volumes:
      - alan-data:/data

volumes:
  alan-data:
YML

cat > .env.example <<'ENV'
# Copy to .env and change what you need. Everything is optional.

# Port on the host where the app is reachable.
ALAN_PORT=8000

# Author of the story commits (set both or none).
#ALAN_GIT_NAME=Your Name
#ALAN_GIT_EMAIL=you@example.org

# The user the server runs as: the files in the data volume belong to this user.
# install.sh sets them to your own user. PUID=0 (or none) runs the server as root.
#PUID=1000
#PGID=1000

# Use another image instead of the one in docker-compose.yml.
#ALAN_IMAGE=git.capjoy.dev/andre-capjoy/alan-a-dale:latest
ENV

[ -e .env ] || { cp .env.example .env; printf 'PUID=%s\nPGID=%s\n' "$(id -u)" "$(id -g)" >> .env; say "Wrote .env (edit it to change the port or the git author)"; }

if [ -n "${ALAN_NO_START:-}" ]; then
  say "Files written. Start with: docker compose up -d"
  exit 0
fi

docker compose pull
docker compose up -d

port=$(sed -n 's/^ALAN_PORT=\([0-9]*\).*/\1/p' .env | tail -n 1)
say "Running: open http://localhost:${port:-8000}/"
say "Models and endpoints are set in the app (Settings). Stop with: docker compose down"
