#!/usr/bin/env bash
# Deploy hacktivism Bonfire branding (hacktivism magician logo + exchange-dark palette).
# Live root: ~/koopa-bonfire/
set -euo pipefail

ROOT="${KOOPA_BONFIRE_ROOT:-$HOME/koopa-bonfire}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." 2>/dev/null && pwd || true)"
BRANDING_DST="$ROOT/data/branding"
ENV_FILE="$ROOT/.env"

install -d -m 755 "$BRANDING_DST"

if [[ -d "$REPO_ROOT/configs/bonfire/assets/img" ]]; then
  BRANDING_SRC="$REPO_ROOT/configs/bonfire/assets/img"
  install -m 644 "$BRANDING_SRC/logo.svg" "$BRANDING_DST/logo.svg"
  install -m 644 "$BRANDING_SRC/favicon.svg" "$BRANDING_DST/favicon.svg"
  install -m 644 "$BRANDING_SRC/logo.png" "$BRANDING_DST/logo.png"
elif [[ ! -f "$BRANDING_DST/logo.svg" ]]; then
  echo "missing $BRANDING_DST/logo.svg (copy assets or run from koopa-admin-log checkout)" >&2
  exit 1
fi

# APP_NAME drives <title> suffix and og:site_name when instance_name is unset in HTML meta.
if [[ -f "$ENV_FILE" ]]; then
  if grep -q '^APP_NAME=' "$ENV_FILE"; then
    sed -i 's/^APP_NAME=.*/APP_NAME=hacktivism bonfire/' "$ENV_FILE"
  else
    echo 'APP_NAME=hacktivism bonfire' >> "$ENV_FILE"
  fi
  if grep -q '^INSTANCE_DESCRIPTION=' "$ENV_FILE"; then
    sed -i 's/^INSTANCE_DESCRIPTION=.*/INSTANCE_DESCRIPTION=Bonfire on hacktivism.ch - FOSS posts and gitbot commits./' "$ENV_FILE"
  else
    echo 'INSTANCE_DESCRIPTION=Bonfire on hacktivism.ch - FOSS posts and gitbot commits.' >> "$ENV_FILE"
  fi
fi

if [[ "$SCRIPT_DIR/apply-branding.exs" != "$ROOT/bin/apply-branding.exs" ]]; then
  install -m 755 "$SCRIPT_DIR/apply-branding.exs" "$ROOT/bin/apply-branding.exs"
fi

echo "Applying instance theme settings via bonfire remote..."
sleep 2
printf '%s\n' "$(cat "$ROOT/bin/apply-branding.exs")" | podman exec -i koopa-bonfire /opt/app/bin/bonfire remote >/tmp/bonfire-branding.log 2>&1 || {
  echo "remote apply failed; see /tmp/bonfire-branding.log" >&2
  tail -30 /tmp/bonfire-branding.log >&2
  exit 1
}
grep -q 'ok branding settings applied' /tmp/bonfire-branding.log

echo "Recreating web container (compose branding volume)..."
cd "$ROOT"
podman-compose up -d --no-deps --force-recreate web

echo "Done. Check https://bonfire.hacktivism.ch/ (hard-reload if cached)."