#!/usr/bin/env bash
#
# webgl-deploy.sh — publish an uploaded Unity WebGL build for speech.neurapy.ai.
#
# You upload each build over SFTP to:
#     /home/neurapyc/webgl/speech/Build/<version>/                     (the WebGL player)
#     /home/neurapyc/webgl/speech/ServerData/<version>/ServerData/WebGL (Addressables bundles)
# and bump scripts/latestwebglversion.txt to the version you want live (e.g. v001).
#
# This script reads that version and creates two symlinks in the Laravel public
# docroot so the build is reachable at the URLs Unity baked in:
#
#   1) Player:   https://speech.neurapy.ai/<version>/index.html
#                <- the URL a super admin pastes into Admin -> OT Provisioning.
#
#   2) Content:  https://speech.neurapy.ai/ServerData/WebGL/...
#                <- Addressables Remote.LoadPath. The build was compiled with the
#                   "WebGL_Remote" profile whose Remote.LoadPath is
#                   https://speech.neurapy.ai/ServerData/[BuildTarget] (BuildTarget =
#                   WebGL). It is VERSION-LESS, so we keep a stable current-version
#                   symlink here and re-point it on each release.
#
# Laravel serves static paths straight from public/ (its .htaccess only rewrites to
# index.php when the file/dir does NOT exist), so real dirs/symlinks under public/
# are served by Apache directly and never hit the framework.
#
# Idempotent: safe to re-run; each link is atomically re-pointed (ln -sfn). Both
# links are driven by the same version, so the player and its content stay in sync.
#
# Usage:
#     ./scripts/webgl-deploy.sh            # version from scripts/latestwebglversion.txt
#     ./scripts/webgl-deploy.sh v002       # explicit version override

set -Eeuo pipefail
umask 022

# ---------------------------------------------------------------------------
# Config — adjust here if paths ever change.
# ---------------------------------------------------------------------------
WEBGL_SRC_ROOT="/home/neurapyc/webgl/speech"                       # where builds are uploaded
DEPLOYPATH="/home/neurapyc/public_html/speech.neurapy.com"         # deployed Laravel app
WEB_ROOT="${DEPLOYPATH}/public"                                 # public docroot (served by Apache)

# Addressables remote content. Must match Unity's active profile Remote.LoadPath.
# WebGL_Remote profile => https://speech.neurapy.ai/ServerData/<BuildTarget>.
LINK_SERVERDATA=1
BUILD_TARGET="WebGL"                                            # Addressables [BuildTarget]
SERVERDATA_LINK="${WEB_ROOT}/ServerData/${BUILD_TARGET}"        # -> current version's bundles

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VERSION_FILE="${SCRIPT_DIR}/latestwebglversion.txt"

# ---------------------------------------------------------------------------
# Logging helpers (same style as cpanel-deploy.sh).
# ---------------------------------------------------------------------------
timestamp() { date '+%Y-%m-%d %H:%M:%S'; }
log()  { printf '[%s] %s\n' "$(timestamp)" "$*"; }
fail() { log "FAILED: $*"; exit 1; }

on_error() {
    local exit_code="$?"
    log "FAILED: stopped at line ${BASH_LINENO[0]:-unknown} with exit code ${exit_code}"
    exit "$exit_code"
}
trap on_error ERR

# ---------------------------------------------------------------------------
# Resolve the version.
# ---------------------------------------------------------------------------
VERSION="${1:-}"

if [ -z "${VERSION}" ]; then
    [ -f "${VERSION_FILE}" ] || fail "No version given and ${VERSION_FILE} not found"
    # First non-empty line; strip CR (file may be edited on Windows) and spaces.
    VERSION="$(tr -d '\r' < "${VERSION_FILE}" | sed -e 's/[[:space:]]//g' -e '/^$/d' | head -n1)"
fi

[ -n "${VERSION}" ] || fail "Could not determine a WebGL version"

# Normalise: allow "001" as shorthand for "v001".
case "${VERSION}" in
    v*) ;;
    [0-9]*) VERSION="v${VERSION}" ;;
esac

# Guard against anything that isn't a plain version token (no path traversal).
if ! printf '%s' "${VERSION}" | grep -Eq '^[A-Za-z0-9._-]+$'; then
    fail "Refusing suspicious version string: '${VERSION}'"
fi

BUILD_SRC="${WEBGL_SRC_ROOT}/Build/${VERSION}"
WEB_LINK="${WEB_ROOT}/${VERSION}"

log "Publishing WebGL version: ${VERSION}"
log "Build source : ${BUILD_SRC}"
log "Web link     : ${WEB_LINK}  ->  https://speech.neurapy.ai/${VERSION}/index.html"

# ---------------------------------------------------------------------------
# Validate the uploaded build.
# ---------------------------------------------------------------------------
[ -d "${BUILD_SRC}" ] || fail "Build folder not found: ${BUILD_SRC} (upload it via SFTP first)"

if [ ! -f "${BUILD_SRC}/index.html" ]; then
    fail "No index.html inside ${BUILD_SRC} — is the Build/<version> folder the WebGL player root?"
fi

[ -d "${WEB_ROOT}" ] || fail "Web root not found: ${WEB_ROOT} (deploy the app first)"

# ---------------------------------------------------------------------------
# 1) Link the player build into the public docroot (atomic re-point).
# ---------------------------------------------------------------------------
if [ -e "${WEB_LINK}" ] && [ ! -L "${WEB_LINK}" ]; then
    fail "${WEB_LINK} exists and is NOT a symlink — refusing to clobber a real directory"
fi

ln -sfn "${BUILD_SRC}" "${WEB_LINK}"
log "Linked player build -> ${WEB_LINK}"

# ---------------------------------------------------------------------------
# 2) Point the Addressables content path at this version's bundles.
#    Baked (version-less) URL: https://speech.neurapy.ai/ServerData/WebGL/
#    Uploaded layout:          webgl/speech/ServerData/<version>/ServerData/WebGL
# ---------------------------------------------------------------------------
if [ "${LINK_SERVERDATA}" = "1" ]; then
    SERVERDATA_SRC="${WEBGL_SRC_ROOT}/ServerData/${VERSION}/ServerData/${BUILD_TARGET}"
    if [ -d "${SERVERDATA_SRC}" ]; then
        if [ -e "${SERVERDATA_LINK}" ] && [ ! -L "${SERVERDATA_LINK}" ]; then
            fail "${SERVERDATA_LINK} exists and is NOT a symlink — refusing to clobber a real directory"
        fi
        mkdir -p "$(dirname "${SERVERDATA_LINK}")"
        ln -sfn "${SERVERDATA_SRC}" "${SERVERDATA_LINK}"
        log "Linked Addressables content -> ${SERVERDATA_LINK}"
        log "   serves: https://speech.neurapy.ai/ServerData/${BUILD_TARGET}/  (Remote.LoadPath)"
    else
        log "WARNING: no Addressables content for ${VERSION} at:"
        log "         ${SERVERDATA_SRC}"
        log "         The game will load the player but fail to fetch remote bundles."
        log "         Upload ServerData/${VERSION}/ServerData/${BUILD_TARGET} and re-run."
    fi
fi

# ---------------------------------------------------------------------------
# Show what the links now resolve to, for the deploy log.
# ---------------------------------------------------------------------------
log "Result:"
ls -ld "${WEB_LINK}" || true
[ "${LINK_SERVERDATA}" = "1" ] && { ls -ld "${SERVERDATA_LINK}" 2>/dev/null || true; }

log "Done. Set the live URL in Admin -> speech Provisioning -> WebGL build:"
log "    https://speech.neurapy.ai/${VERSION}/index.html"
