#!/usr/bin/env bash
set -Eeuo pipefail

SERVICE_NAME="${AGRARIAN_TILE_SERVICE_NAME:-agrarian-tile-delivery}"
SERVER_NAME="${AGRARIAN_TILE_SERVER_NAME:-_}"
WEB_ROOT="${AGRARIAN_TILE_WEB_ROOT:-/srv/agrarian/tile-delivery/public}"
ARCHIVE_PATH="${1:-}"

log() {
  printf '[agrarian-tile-server] %s\n' "$*"
}

if [[ "${EUID}" -ne 0 ]]; then
  printf 'Run this script as root or with sudo.\n' >&2
  exit 1
fi

apt-get update
apt-get install -y nginx ca-certificates curl

mkdir -p "${WEB_ROOT}"

if [[ -n "${ARCHIVE_PATH}" ]]; then
  if [[ ! -f "${ARCHIVE_PATH}" ]]; then
    printf 'Tile package archive not found: %s\n' "${ARCHIVE_PATH}" >&2
    exit 1
  fi
  tar -xzf "${ARCHIVE_PATH}" -C "${WEB_ROOT}"
fi

chown -R www-data:www-data "$(dirname "${WEB_ROOT}")"

cat > "/etc/nginx/sites-available/${SERVICE_NAME}" <<NGINX
server {
    listen 80;
    listen [::]:80;
    server_name ${SERVER_NAME};

    root ${WEB_ROOT};
    index manifest.json;

    access_log /var/log/nginx/${SERVICE_NAME}.access.log;
    error_log /var/log/nginx/${SERVICE_NAME}.error.log;

    add_header X-Content-Type-Options nosniff always;
    add_header Cache-Control "public, max-age=300" always;

    location = /health {
        access_log off;
        default_type text/plain;
        return 200 "ok\n";
    }

    location / {
        try_files \$uri =404;
    }
}
NGINX

ln -sfn "/etc/nginx/sites-available/${SERVICE_NAME}" "/etc/nginx/sites-enabled/${SERVICE_NAME}"
rm -f /etc/nginx/sites-enabled/default
nginx -t
systemctl enable --now nginx
systemctl reload nginx

log "Tile delivery server ready."
log "Web root: ${WEB_ROOT}"
log "Health: http://SERVER_IP/health"
log "Manifest: http://SERVER_IP/manifest.json"
