#!/usr/bin/env bash

# Remove legacy post-update hook if present
POST_UPDATE_HOOK="${APP_DATA_DIR}/hooks/post-update"
if [[ -e "${POST_UPDATE_HOOK}" ]]; then
  echo "App: ${APP_ID} - Removing '${POST_UPDATE_HOOK}'"
  rm -f -- "${POST_UPDATE_HOOK}" || echo "App: ${APP_ID} - Warning: failed to remove '${POST_UPDATE_HOOK}'"
fi

# If ${APP_DATA_DIR}/data/fulcrum-logs doesn't exist, we create it and set 1000:1000 ownership
if [[ ! -d "${APP_DATA_DIR}/data/fulcrum-logs" ]]; then
  mkdir -p "${APP_DATA_DIR}/data/fulcrum-logs"
  chown 1000:1000 "${APP_DATA_DIR}/data/fulcrum-logs"
fi

# We do a one-time re-sync for pre-2.0 users by clearing the old fulcrum data if present
# Why we delete instead of attempting a one-time on-start `--db-upgrade`:
# - Fulcrum 2.0 uses a new, incompatible DB format; 1.x requires `--db-upgrade` to convert
# - The 1.x -> 2.0 upgrade is irreversible and unsafe to interrupt; a restart during upgrade
#   can destroy both the old and new DBs (see Fulcrum 2.0 release notes)
# - We cannot guarantee users won't restart the app mid-upgrade, which can take several hours on mainnet.
#   and users would get no feedback from the app at all during that time.
# - A flagged one-time delete followed by a fresh sync is deterministic, idempotent, and avoids
#   partial migrations or bricked states if users restart at the wrong time
FULCRUM_DATA_DIR="${APP_DATA_DIR}/data/fulcrum"
POST_2_0_FLAG="${APP_DATA_DIR}/POST_2_0_VERSION"

mkdir -p "${FULCRUM_DATA_DIR}"

if [[ ! -f "${POST_2_0_FLAG}" ]]; then
  # Check if directory has any entries (files or dirs), including dotfiles
  if [[ -n "$(find "${FULCRUM_DATA_DIR}" -mindepth 1 -maxdepth 1 -print -quit 2>/dev/null)" ]]; then
    echo "App: ${APP_ID} - Pre-2.0 data detected, clearing '${FULCRUM_DATA_DIR}' once"
    # Remove all entries safely (handles dotfiles and names with spaces)
    find "${FULCRUM_DATA_DIR}" -mindepth 1 -maxdepth 1 -exec rm -rf {} +
  fi
  touch "${POST_2_0_FLAG}"
fi

# Delay booting Fulcrum until the RPC Tor Hidden Service is ready

HIDDEN_SERVICE_FILE="${TOR_DATA_DIR}/app-${APP_ID}-rpc/hostname"

if [[ -f "${HIDDEN_SERVICE_FILE}" ]]; then
	exit
fi

"${UMBREL_ROOT}/scripts/app" compose "${APP_ID}" up --detach fulcrum
"${UMBREL_ROOT}/scripts/app" compose "${APP_ID}" up --detach tor

echo "App: ${APP_ID} - Generating Tor Hidden Service..."

for attempt in $(seq 1 100); do
	if [[ -f "${HIDDEN_SERVICE_FILE}" ]]; then
		echo "App: ${APP_ID} - Hidden service file created successfully!"
		break
	fi
	sleep 0.1
done

if [[ ! -f "${HIDDEN_SERVICE_FILE}" ]]; then
	echo "App: ${APP_ID} - Hidden service file wasn't created"
fi
