#!/usr/bin/env bash
# Tilecast Server installer. The docs build embeds the production Compose file
# below, so installing does not require Git or a second configuration download.
set -euo pipefail

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

usage() {
  cat <<'HELP'
Install Tilecast Server with Docker Compose (new installations only).

Usage: bash tilecast-install.sh [options]
  --url URL         Address browsers and Players will use (default: http://localhost:8080)
                    HTTP: localhost or a private IPv4 address; HTTPS: configure your own proxy.
  --port PORT       Host port (default: HTTP URL port, or 8080 for HTTPS).
  --directory PATH  New installation directory (default: $HOME/tilecast).
  --version TAG     stable (default) or a published X.Y.Z version.
  --digest DIGEST   With --version X.Y.Z, pin that release's verified Server
                    image digest (sha256: followed by 64 hex digits).
  --help            Show this help.

Requires a local Docker daemon, Docker Compose v2 with --wait and
--wait-timeout, and OpenSSL. Loopback installs require Docker Engine 28.0.0
or later. No sudo, Docker installation, firewall changes, or automatic
upgrades are performed.
HELP
}

# This literal is replaced from deploy/docker/compose.yml at docs build time.
write_compose() {
  cat <<'TILECAST_COMPOSE_YAML'
name: tilecast

services:
  server:
    # Normal installs run a published Stable image. TILECAST_VERSION is the
    # one place that selects the installed server version: keep the stable
    # alias to follow Stable releases, or pin an explicit release such as
    # 0.11.0 for controlled upgrades. See compose.dev.yml for source builds.
    image: ghcr.io/gbyo/tilecast-server:${TILECAST_VERSION:-stable}
    restart: unless-stopped
    environment:
      TILECAST_ENV: production
      TILECAST_HTTP_ADDR: :8080
      TILECAST_DATABASE_URL: postgres://${POSTGRES_USER:-tilecast}:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}@postgres:5432/${POSTGRES_DB:-tilecast}?sslmode=disable
      TILECAST_PUBLIC_URL: ${TILECAST_PUBLIC_URL:-http://localhost:8080}
      TILECAST_COOKIE_SECURE: ${TILECAST_COOKIE_SECURE:-false}
      TILECAST_SESSION_TTL: ${TILECAST_SESSION_TTL:-24h}
      TILECAST_PRESENTATION_NETWORK_KEY: ${TILECAST_PRESENTATION_NETWORK_KEY:-}
      TILECAST_SECRETS_KEY_FILE: ${TILECAST_SECRETS_KEY_FILE:-/data/secrets/kek.json}
      TILECAST_WEBAUTHN_RP_ID: ${TILECAST_WEBAUTHN_RP_ID:-}
      TILECAST_WEBAUTHN_ORIGINS: ${TILECAST_WEBAUTHN_ORIGINS:-}
      TILECAST_TRUSTED_PROXIES: ${TILECAST_TRUSTED_PROXIES:-}
      TILECAST_LOG_LEVEL: ${TILECAST_LOG_LEVEL:-info}
      TILECAST_MDNS_ENABLED: ${TILECAST_MDNS_ENABLED:-false}
      TILECAST_FONT_CATALOG_ENABLED: ${TILECAST_FONT_CATALOG_ENABLED:-true}
      TILECAST_MOSAIC_DISABLED: ${TILECAST_MOSAIC_DISABLED:-false}
      TILECAST_MEDIA_ROOT: /data/media
      TILECAST_MAX_UPLOAD_BYTES: ${TILECAST_MAX_UPLOAD_BYTES:-10737418240}
      TILECAST_MEDIA_WORKERS: ${TILECAST_MEDIA_WORKERS:-2}
      TILECAST_MEDIA_RESERVED_FREE_BYTES: ${TILECAST_MEDIA_RESERVED_FREE_BYTES:-1073741824}
      TILECAST_FFMPEG_PATH: /usr/bin/ffmpeg
      TILECAST_FFPROBE_PATH: /usr/bin/ffprobe
      TILECAST_VIDEO_MAX_WIDTH: ${TILECAST_VIDEO_MAX_WIDTH:-1920}
      TILECAST_VIDEO_MAX_HEIGHT: ${TILECAST_VIDEO_MAX_HEIGHT:-1080}
      TILECAST_VIDEO_MAX_FRAME_RATE: ${TILECAST_VIDEO_MAX_FRAME_RATE:-60}
      TILECAST_KEEP_ORIGINALS: ${TILECAST_KEEP_ORIGINALS:-true}
      TILECAST_MAX_SCHEDULES: ${TILECAST_MAX_SCHEDULES:-1000}
      TILECAST_MAX_SCHEDULE_TARGETS: ${TILECAST_MAX_SCHEDULE_TARGETS:-250}
      TILECAST_MAX_GROUPS_PER_SCREEN: ${TILECAST_MAX_GROUPS_PER_SCREEN:-50}
      TILECAST_SCHEDULE_PREFETCH_DAYS: ${TILECAST_SCHEDULE_PREFETCH_DAYS:-14}
      TILECAST_SCHEDULE_ACTIVATION_GRACE_SECONDS: ${TILECAST_SCHEDULE_ACTIVATION_GRACE_SECONDS:-30}
      TILECAST_CLOCK_SKEW_WARNING_SECONDS: ${TILECAST_CLOCK_SKEW_WARNING_SECONDS:-300}
      TILECAST_WEBSITE_ALLOW_PRIVATE_HTTP: ${TILECAST_WEBSITE_ALLOW_PRIVATE_HTTP:-false}
      TILECAST_WEBSITE_DEFAULT_TIMEOUT_SECONDS: ${TILECAST_WEBSITE_DEFAULT_TIMEOUT_SECONDS:-20}
      TILECAST_WEBSITE_MAX_TIMEOUT_SECONDS: ${TILECAST_WEBSITE_MAX_TIMEOUT_SECONDS:-120}
      TILECAST_WEBSITE_MIN_REFRESH_SECONDS: ${TILECAST_WEBSITE_MIN_REFRESH_SECONDS:-30}
      TILECAST_WEBSITE_MAX_ALLOWED_HOSTS: ${TILECAST_WEBSITE_MAX_ALLOWED_HOSTS:-25}
      TILECAST_WEBSITE_MAX_ASSETS: ${TILECAST_WEBSITE_MAX_ASSETS:-500}
      TILECAST_SOURCE_ALLOW_PRIVATE_NETWORKS: ${TILECAST_SOURCE_ALLOW_PRIVATE_NETWORKS:-false}
      TILECAST_SOURCE_FETCH_TIMEOUT_SECONDS: ${TILECAST_SOURCE_FETCH_TIMEOUT_SECONDS:-15}
      TILECAST_SOURCE_MAX_RESPONSE_BYTES: ${TILECAST_SOURCE_MAX_RESPONSE_BYTES:-2097152}
      TILECAST_SOURCE_MAX_REDIRECTS: ${TILECAST_SOURCE_MAX_REDIRECTS:-3}
      TILECAST_SOURCE_MIN_REFRESH_SECONDS: ${TILECAST_SOURCE_MIN_REFRESH_SECONDS:-300}
      TILECAST_SOURCE_MAX_REFRESH_SECONDS: ${TILECAST_SOURCE_MAX_REFRESH_SECONDS:-86400}
      TILECAST_AIR_QUALITY_BASE_URL: ${TILECAST_AIR_QUALITY_BASE_URL:-https://air-quality-api.open-meteo.com}
      TILECAST_MAX_TAKEOVER_DURATION_HOURS: ${TILECAST_MAX_TAKEOVER_DURATION_HOURS:-24}
      TILECAST_MAX_TAKEOVER_TARGETS: ${TILECAST_MAX_TAKEOVER_TARGETS:-250}
      TILECAST_MAX_PENDING_COMMANDS_PER_SCREEN: ${TILECAST_MAX_PENDING_COMMANDS_PER_SCREEN:-50}
      TILECAST_DEFAULT_COMMAND_EXPIRY_MINUTES: ${TILECAST_DEFAULT_COMMAND_EXPIRY_MINUTES:-10}
      TILECAST_IDENTIFY_SCREEN_MAX_SECONDS: ${TILECAST_IDENTIFY_SCREEN_MAX_SECONDS:-120}
      TILECAST_COMMAND_RETENTION_DAYS: ${TILECAST_COMMAND_RETENTION_DAYS:-30}
      TILECAST_UPDATE_ROOT: /data/updates
      TILECAST_UPDATE_MANIFEST_PUBLIC_KEY: ${TILECAST_UPDATE_MANIFEST_PUBLIC_KEY:-}
      TILECAST_PLAYER_RELEASE_ML_DSA_POLICY: ${TILECAST_PLAYER_RELEASE_ML_DSA_POLICY:-}
      TILECAST_UPDATE_MAX_APK_BYTES: ${TILECAST_UPDATE_MAX_APK_BYTES:-536870912}
      TILECAST_UPDATE_RETENTION_DAYS: ${TILECAST_UPDATE_RETENTION_DAYS:-90}
      TILECAST_RELEASE_PUBLISH_TOKEN: ${TILECAST_RELEASE_PUBLISH_TOKEN:-}
      TILECAST_GITHUB_TOKEN: ${TILECAST_GITHUB_TOKEN:-}
      TILECAST_GITHUB_CLIENT_ID: ${TILECAST_GITHUB_CLIENT_ID:-}
      TILECAST_SMTP_HOST: ${TILECAST_SMTP_HOST:-}
      TILECAST_SMTP_PORT: ${TILECAST_SMTP_PORT:-587}
      TILECAST_SMTP_USERNAME: ${TILECAST_SMTP_USERNAME:-}
      TILECAST_SMTP_PASSWORD: ${TILECAST_SMTP_PASSWORD:-}
      TILECAST_SMTP_TLS: ${TILECAST_SMTP_TLS:-starttls}
      TILECAST_SMTP_ALLOW_INSECURE: ${TILECAST_SMTP_ALLOW_INSECURE:-false}
      TILECAST_SMTP_ALLOW_PLAINTEXT_AUTH: ${TILECAST_SMTP_ALLOW_PLAINTEXT_AUTH:-false}
    ports:
      - "${TILECAST_BIND_ADDRESS:+${TILECAST_BIND_ADDRESS}:}${TILECAST_PORT:-8080}:8080"
    volumes:
      - tilecast_data:/data
    depends_on:
      postgres:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "wget", "-q", "--spider", "http://127.0.0.1:8080/readyz"]
      interval: 15s
      timeout: 4s
      retries: 5
      start_period: 10s

  postgres:
    image: postgres:17-alpine
    restart: unless-stopped
    environment:
      POSTGRES_DB: ${POSTGRES_DB:-tilecast}
      POSTGRES_USER: ${POSTGRES_USER:-tilecast}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
      interval: 5s
      timeout: 5s
      retries: 10

  cloudflared:
    image: cloudflare/cloudflared:latest
    profiles: ["tunnel"]
    restart: unless-stopped
    command: tunnel --no-autoupdate run
    environment:
      TUNNEL_TOKEN: ${CLOUDFLARE_TUNNEL_TOKEN:-}
    depends_on:
      server:
        condition: service_healthy

volumes:
  tilecast_data:
  postgres_data:
TILECAST_COMPOSE_YAML
}

port_valid() {
  [[ $1 =~ ^[1-9][0-9]{0,4}$ ]] && (( 10#$1 <= 65535 ))
}

private_ipv4() {
  local address=$1 a b c d octet
  [[ $address =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] || return 1
  IFS=. read -r a b c d <<< "$address"
  for octet in "$a" "$b" "$c" "$d"; do
    [[ $octet =~ ^(0|[1-9][0-9]{0,2})$ ]] && (( 10#$octet <= 255 )) || return 1
  done
  (( a == 10 || (a == 172 && b >= 16 && b <= 31) || (a == 192 && b == 168) ))
}

# Resolve the effective endpoint using Docker's environment precedence, then
# pin it so a concurrent `docker context use` cannot redirect the installation.
select_local_daemon() {
  local context endpoint
  if [[ -n ${DOCKER_CONTEXT:-} || -z ${DOCKER_HOST:-} ]]; then
    context=$(docker context show) || fail 'Could not determine the Docker context.'
    endpoint=$(docker context inspect "$context" --format '{{.Endpoints.docker.Host}}') ||
      fail 'Could not inspect the Docker context.'
  else
    endpoint=$DOCKER_HOST
  fi
  case "$endpoint" in
    unix:///*|npipe:////./pipe/*) ;;
    *) fail 'The installer requires a local Docker socket. Run it on the server itself, not through a remote Docker context or DOCKER_HOST.' ;;
  esac
  unset DOCKER_CONTEXT
  export DOCKER_HOST="$endpoint"
}

require_loopback_isolation() {
  local engine_version
  engine_version=$(docker version --format '{{.Server.Version}}') ||
    fail 'Could not determine the Docker Engine version.'
  # Older engines can expose localhost-published ports to peers on the LAN.
  # Reject unknown and prerelease versions rather than assume isolation.
  [[ $engine_version =~ ^([0-9]+)\.[0-9]+\.[0-9]+(\+[^[:space:]]+)?$ ]] &&
    (( 10#${BASH_REMATCH[1]} >= 28 )) ||
    fail 'Loopback installs require Docker Engine 28.0.0 or later to restrict setup to this host. Upgrade Docker before installing.'
}

check_existing_project() {
  local containers project_volumes volumes
  containers=$(docker ps -a --filter label=com.docker.compose.project=tilecast --quiet) ||
    fail 'Could not inspect existing Docker containers.'
  project_volumes=$(docker volume ls --filter label=com.docker.compose.project=tilecast --quiet) ||
    fail 'Could not inspect existing Docker volumes.'
  volumes=$(docker volume ls --quiet) || fail 'Could not inspect existing Docker volumes.'
  if [[ -n $containers || -n $project_volumes ]] ||
    grep -qxE 'tilecast_(postgres_data|tilecast_data)' <<< "$volumes"; then
    fail 'An existing Tilecast Docker project or data volume was found. Nothing was changed in that project. Use the update instructions at https://tilecast.org/administration/server-updates/'
  fi
}

installer_lock_id=''
release_installer_lock() {
  if [[ -n $installer_lock_id ]]; then
    docker rm -v "$installer_lock_id" >/dev/null ||
      printf 'Tilecast: Could not remove the installer lock. See the installation guide before retrying.\n' >&2
  fi
}

acquire_installer_lock() {
  # Docker reserves container names atomically on the daemon, even across
  # installer processes using different directories or Unix accounts. This
  # container is never started and must not use the Compose project label.
  installer_lock_id=$(docker create --name tilecast-install-lock \
    --label org.tilecast.installer-lock=true --network none --tmpfs /data \
    --entrypoint /bin/true "ghcr.io/gbyo/tilecast-server:$1") ||
    fail 'Could not acquire the Tilecast installer lock. Another installer may be running. See https://tilecast.org/installation/ before retrying.'
  [[ $installer_lock_id =~ ^[a-f0-9]{64}$ ]] || fail 'Docker returned an invalid installer lock ID.'
  trap release_installer_lock EXIT
  trap 'exit 130' INT
  trap 'exit 143' TERM
}

main() {
  local url='' port='' directory="${HOME:-}/tilecast" version=stable digest=''
  while (($#)); do
    case "$1" in
      --help|-h) usage; return 0 ;;
      --url|--port|--directory|--version|--digest)
        [[ $# -ge 2 && -n $2 && $2 != --* ]] || fail "Missing value for $1."
        case "$1" in
          --url) url=$2 ;;
          --port) port=$2 ;;
          --directory) directory=$2 ;;
          --version) version=$2 ;;
          --digest) digest=$2 ;;
        esac
        shift 2 ;;
      *) fail "Unknown option $1. Run with --help." ;;
    esac
  done

  [[ -n ${HOME:-} || $directory != /tilecast ]] || fail 'Set HOME or supply --directory.'
  [[ $version == stable || $version =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] ||
    fail 'Choose stable or a published numeric version (X.Y.Z).'
  if [[ -n $digest ]]; then
    # Docker pulls a tag@digest reference by digest. The tag keeps the
    # selected release readable and matches the Supervisor's Container export.
    [[ $version != stable ]] || fail 'Use --digest with the --version X.Y.Z release that it was verified for.'
    [[ $digest =~ ^sha256:[0-9a-f]{64}$ ]] || fail 'Use sha256: followed by 64 lowercase hex digits.'
    version="$version@$digest"
  fi
  [[ -n $directory && $directory != *$'\n'* && $directory != *$'\r'* ]] ||
    fail 'Choose a valid installation directory.'
  [[ $directory == /* ]] || directory="$PWD/$directory"
  [[ ! -e $directory && ! -L $directory ]] ||
    fail "Installation directory already exists: $directory. Existing installations must be updated manually."

  command -v docker >/dev/null || fail 'Install Docker Engine and Docker Compose v2 first: https://docs.docker.com/engine/install/'
  select_local_daemon
  local compose_version compose_up_help
  compose_version=$(docker compose version --short 2>/dev/null) ||
    fail 'Docker Compose v2 is required: https://docs.docker.com/compose/install/'
  [[ $compose_version =~ ^v?[2-9][0-9]*\. || $compose_version =~ ^v?[1-9][0-9]+\. ]] ||
    fail 'Docker Compose v2 or later is required.'
  compose_up_help=$(docker compose up --help) || fail 'Could not inspect Docker Compose startup options.'
  if ! grep -Eq '(^|[[:space:]])--wait([[:space:]]|$)' <<< "$compose_up_help" ||
    ! grep -Eq '(^|[[:space:]])--wait-timeout([[:space:]]|$)' <<< "$compose_up_help"; then
    fail 'Docker Compose must support --wait and --wait-timeout. Update Docker Compose before installing.'
  fi
  docker info >/dev/null 2>&1 ||
    fail 'Cannot reach the Docker daemon. Start Docker and use an account with access to it.'
  command -v openssl >/dev/null || fail 'Install OpenSSL first to generate a database password.'

  # The shell environment takes precedence over .env in Compose. Do not let a
  # previous deployment's variables silently replace the new configuration.
  local variable
  while IFS= read -r variable; do
    case "$variable" in
      TILECAST_*|POSTGRES_*|COMPOSE_*|CLOUDFLARE_TUNNEL_TOKEN)
        fail "Unset $variable before running the installer."
        ;;
    esac
  done < <(compgen -e)

  if [[ -z $url ]]; then
    [[ -z $port ]] || port_valid "$port" || fail 'Port must be between 1 and 65535.'
    local default_url="http://localhost:${port:-8080}"
    # Prompt on a real terminal even when the installer arrives via curl | bash.
    # Without a terminal the local-only default is safe for unattended runs.
    if ( : </dev/tty ) 2>/dev/null; then
      printf '%s\n' 'Tilecast Server' 'Enter the address Studio and Players will use.' \
        'For a trusted LAN, use this host’s private IPv4 address (for example http://192.168.1.10:8080).' \
        'For remote access, use your HTTPS hostname and configure a reverse proxy.' >&2
      printf 'Server address [%s]: ' "$default_url" >&2
      read -r url </dev/tty || fail 'No address entered.'
    fi
    url=${url:-$default_url}
  fi

  # Restrict values to an origin (no user info, path, query, whitespace or
  # shell/Compose metacharacters). HTTP is allowed only on explicit local
  # addresses. HTTPS terminates at an operator-managed reverse proxy.
  url=${url%/}
  [[ $url =~ ^(https?)://([A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?)(:([0-9]{1,5}))?$ ]] ||
    fail 'Use an HTTP or HTTPS origin without a path, query, or credentials.'
  local scheme=${BASH_REMATCH[1]} host=${BASH_REMATCH[2]} public_port=${BASH_REMATCH[5]}
  local bind=127.0.0.1 secure=true
  [[ -z $public_port ]] || port_valid "$public_port" || fail 'Invalid port in the server address.'
  if [[ $scheme == http ]]; then
    secure=false
    if [[ $host == localhost || $host == 127.0.0.1 ]]; then
      bind=127.0.0.1
    elif private_ipv4 "$host"; then
      bind=$host
    else
      fail 'Plain HTTP requires localhost or a private IPv4 address. Use HTTPS for a public hostname.'
    fi
    public_port=${public_port:-80}
    [[ -z $port || $port == "$public_port" ]] ||
      fail 'For direct HTTP access, --port must match the server URL port.'
    port=$public_port
  else
    port=${port:-8080}
  fi
  port_valid "$port" || fail 'Port must be between 1 and 65535.'
  if [[ $bind == 127.0.0.1 ]]; then
    require_loopback_isolation
  fi

  local compose password
  compose=$(write_compose)
  [[ $compose == 'name: tilecast'* && $compose != *'@TILECAST_COMPOSE_YAML@'* ]] ||
    fail 'The installer package is incomplete. Download it from https://tilecast.org/install.sh.'
  password=$(openssl rand -hex 32) || fail 'Could not generate a database password.'
  [[ $password =~ ^[a-f0-9]{64}$ ]] || fail 'Could not generate a valid database password.'

  # Do not hold the lock while waiting for interactive input. Recheck after
  # acquiring it: another process could finish between inspection and create.
  check_existing_project
  acquire_installer_lock "$version"
  check_existing_project

  umask 077
  mkdir -- "$directory" || fail "Could not create $directory. Choose a new directory with an existing parent."
  printf '%s\n' "$compose" > "$directory/compose.yml"
  {
    printf 'TILECAST_VERSION=%s\n' "$version"
    printf 'POSTGRES_PASSWORD=%s\n' "$password"
    printf 'TILECAST_BIND_ADDRESS=%s\n' "$bind"
    printf 'TILECAST_PORT=%s\n' "$port"
    printf 'TILECAST_PUBLIC_URL=%s\n' "$url"
    printf 'TILECAST_COOKIE_SECURE=%s\n' "$secure"
  } > "$directory/.env"
  unset password

  printf '\nStarting Tilecast Server (%s) in %s\n' "$version" "$directory"
  local started=false
  local -a dc=(docker compose --project-name tilecast --project-directory "$directory" --env-file "$directory/.env" -f "$directory/compose.yml")
  if "${dc[@]}" config --quiet && "${dc[@]}" pull server postgres; then
    # A manually started deployment does not take the installer lock. Check
    # again after the potentially long image pull, just before creating services.
    check_existing_project
    if "${dc[@]}" up -d --wait --wait-timeout 180 server postgres; then
      started=true
    fi
  fi
  if [[ $started != true ]]; then
    printf 'Tilecast could not start or did not become ready. Your configuration and any data have been preserved.\n' >&2
    printf 'Inspect the logs: cd %q && docker compose logs\n' "$directory" >&2
    exit 1
  fi

  printf '\nTilecast Server is ready.\n'
  if [[ $scheme == https ]]; then
    printf 'Configure your TLS reverse proxy to forward to http://127.0.0.1:%s before visiting Studio.\n' "$port"
  elif [[ $bind == 127.0.0.1 ]]; then
    printf 'Studio is accessible only on this host. For network access, configure a reachable address or HTTPS proxy.\n'
  else
    printf 'HTTP is unencrypted. Keep this address on a trusted LAN; do not forward the port to the internet.\n'
  fi
  printf 'Open %s to create your organization and first Owner account.\n' "$url"
  printf 'Configuration: %s/.env (keep this file private and back it up securely).\n' "$directory"
  printf 'Manage the services: cd %q && docker compose ps\n' "$directory"
  printf 'Documentation: https://tilecast.org/installation/\n'
}

# Keep the invocation last so a truncated streamed download cannot start an
# installation with a partially received function or Compose file.
main "$@"
