#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=scripts/common.sh
source "$SCRIPT_DIR/scripts/common.sh"

REUSE_ENV_FROM=""

usage() {
  cat <<'USAGE'
Usage: ./upgrade.sh [--reuse-env-from /path/to/.env]
USAGE
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --reuse-env-from)
      REUSE_ENV_FROM="$2"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      die "unknown option: $1"
      ;;
  esac
done

if [[ -n "$REUSE_ENV_FROM" ]]; then
  [[ -f "$REUSE_ENV_FROM" ]] || die "missing reuse env file: $REUSE_ENV_FROM"
  if [[ ! -f "$ENV_FILE" ]]; then
    cp "$REUSE_ENV_FROM" "$ENV_FILE"
    log "copied existing env into new package: $REUSE_ENV_FROM -> $ENV_FILE"
  else
    log "keeping existing env at $ENV_FILE; reuse source ignored: $REUSE_ENV_FROM"
  fi
fi

load_env
create_data_dirs
install_docker_if_missing
load_installer_images
ensure_binfmt_if_needed
verify_runtime_image
verify_monitor_images
compose_cmd --profile core --profile sidecar --profile monitor up -d --force-recreate
"$SCRIPT_DIR/status.sh" --brief || true
