#!/bin/bash
# One-shot install of Photon 0.5.0 (last Elasticsearch-backed release) on satra.
# Photon 0.6+ uses OpenSearch and is incompatible with the country-level extracts
# graphhopper still publishes (which are ES format). Verified working 2026-05-08.
#
# After install, start as a service: see vreaudigital-photon.service in this dir.
#
# Prerequisite: the RO ES extract is already at /opt/photon/photon_data
# (downloaded by setup-photon.sh from photon-db-ro-DDMMYY.tar.bz2).

set -euo pipefail

PHOTON_DIR=/opt/photon
PHOTON_VERSION=0.5.0
JAR_URL=https://github.com/komoot/photon/releases/download/${PHOTON_VERSION}/photon-${PHOTON_VERSION}.jar

log() { echo "[$(date '+%H:%M:%S')] $1"; }

log "=== Photon ${PHOTON_VERSION} install ==="

# 1. JDK 21 (works with Photon 0.5.0; 0.5 requires JDK 11+).
if ! command -v java >/dev/null 2>&1; then
  log "Installing openjdk-21-jre-headless..."
  sudo apt-get install -y openjdk-21-jre-headless
fi
java --version

# 2. Photon JAR
if [ ! -s "$PHOTON_DIR/photon-${PHOTON_VERSION}.jar" ]; then
  log "Downloading photon-${PHOTON_VERSION}.jar (~38MB)..."
  sudo curl -fL -o "$PHOTON_DIR/photon-${PHOTON_VERSION}.jar" "$JAR_URL"
  sudo chown bulibasa:bulibasa "$PHOTON_DIR/photon-${PHOTON_VERSION}.jar"
else
  log "JAR already on disk."
fi

# 3. Sanity-check the extract directory
if [ ! -d "$PHOTON_DIR/photon_data/elasticsearch" ]; then
  log "FATAL: $PHOTON_DIR/photon_data/elasticsearch missing — run setup-photon.sh first."
  exit 1
fi
sudo chown -R bulibasa:bulibasa "$PHOTON_DIR/photon_data"

# 4. Pre-create log + service file expectations
sudo touch /var/log/vreaudigital-photon.log
sudo chown bulibasa:bulibasa /var/log/vreaudigital-photon.log

log "=== Install done. Start with: ==="
log "  cd $PHOTON_DIR && nohup java -Xmx8G -jar photon-${PHOTON_VERSION}.jar -data-dir $PHOTON_DIR -listen-port 2322 </dev/null >>/var/log/vreaudigital-photon.log 2>&1 &"
log "Or install systemd unit: sudo ln -sf $PHOTON_DIR/../vreaudigital/services/seap-scraper/cron/vreaudigital-photon.service /etc/systemd/system/ && sudo systemctl enable --now vreaudigital-photon"
log "Smoke test: curl 'http://localhost:2322/api?q=Bucuresti&limit=1'"
