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

# ── LibNovel — production management script ───────────────────────────────────
# Prerequisites on the server:
#   - docker + docker compose plugin
#   - doppler CLI authenticated (doppler setup run once in the repo directory)
#   - docker-compose.yml present in the same directory as this script
#
# Usage: ./libnovel.sh <command> [service]
#
#   up              Start all services (detached)
#   down            Stop all services
#   restart         Stop then start all services
#   restart <svc>   Restart a single service
#   pull            Pull latest images from Docker Hub (uses GIT_TAG from Doppler)
#   update          Pull images then recreate containers
#   logs            Tail all logs
#   logs <svc>      Tail a specific service
#   ps              Show running containers
#   shell <svc>     Open a shell in a running container
#   init            Run one-shot init containers
#   secrets         Print all Doppler secrets (debug)
# ──────────────────────────────────────────────────────────────────────────────

DC="doppler run -- docker compose"
CMD="${1:-help}"
SVC="${2:-}"

case "$CMD" in
  up)
    $DC up -d
    ;;

  down)
    $DC down
    ;;

  restart)
    if [[ -n "$SVC" ]]; then
      $DC restart "$SVC"
    else
      $DC down
      $DC up -d
    fi
    ;;

  pull)
    $DC pull backend runner ui caddy
    ;;

  update)
    $DC pull backend runner ui caddy
    $DC up -d
    ;;

  logs)
    if [[ -n "$SVC" ]]; then
      $DC logs -f --tail=100 "$SVC"
    else
      $DC logs -f --tail=50
    fi
    ;;

  ps)
    $DC ps
    ;;

  shell)
    [[ -z "$SVC" ]] && { echo "Usage: $0 shell <service>"; exit 1; }
    $DC exec "$SVC" sh
    ;;

  init)
    $DC run --rm minio-init
    $DC run --rm pb-init
    $DC run --rm postgres-init
    ;;

  secrets)
    doppler secrets --project libnovel --config prd
    ;;

  help|*)
    echo "Usage: $0 <command> [service]"
    echo ""
    echo "  up              Start all services"
    echo "  down            Stop all services"
    echo "  restart         Full restart"
    echo "  restart <svc>   Restart one service"
    echo "  pull            Pull latest images from Docker Hub"
    echo "  update          Pull + recreate containers"
    echo "  logs            Tail all logs"
    echo "  logs <svc>      Tail one service"
    echo "  ps              Show running containers"
    echo "  shell <svc>     Shell into a container"
    echo "  init            Run init containers (first-time setup)"
    echo "  secrets         Print Doppler secrets"
    ;;
esac
