#!/bin/sh
# uploy launcher (portable build) — execs the unified seamain entry.
# No args → foreground daemon; args → CLI subcommand tree (e.g.
# `uploy autostart install`, `uploy deploy <id>`). Honors UPLOY_HOME
# for the data dir; refuses to double-start a daemon invocation.
# K-585: resolve symlinks before deriving DIR — the installer links
# /usr/local/bin/uploy to this launcher, and dirname of the LINK would
# point at /usr/local instead of the install tree.
SELF="$0"
if command -v readlink >/dev/null 2>&1 && RESOLVED=$(readlink -f "$0" 2>/dev/null) && [ -n "$RESOLVED" ]; then
  SELF="$RESOLVED"
fi
DIR=$(cd "$(dirname "$SELF")/.." && pwd)
if [ -n "$UPLOY_HOME" ]; then DATA_DIR="$UPLOY_HOME"; else DATA_DIR="$HOME/.uploy"; fi
mkdir -p "$DATA_DIR"
PID_FILE="$DATA_DIR/server.pid"
# Only the no-arg (daemon) invocation is guarded against double-start; a
# CLI subcommand is a one-shot and may run alongside the daemon.
if [ $# -eq 0 ] && [ -f "$PID_FILE" ]; then
  PID=$(cat "$PID_FILE" 2>/dev/null || true)
  if [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; then
    echo "uploy already running (pid $PID). Dashboard: http://localhost:8765"; exit 0
  fi
fi
export NODE_ENV=production
# K-591: the stamped release version — the update checker's baseline
# (UPLOY_VERSION ?? readCurrentVersion() ?? '0.1.0') honors this env first.
export UPLOY_VERSION='0.1.12'
# K-585 sweep: fail with a clear message instead of node's raw
# MODULE_NOT_FOUND when the launcher was copied/moved out of the install
# tree (symlink resolution is the supported invocation path).
if [ ! -f "$DIR/server/dist/seamain.js" ]; then
  echo "uploy: install root not found at $DIR — invoked via a copied/moved launcher?" >&2
  echo "uploy: run the installer again, or invoke $(readlink -f "$0" 2>/dev/null || echo $0) directly." >&2
  exit 8
fi
exec node "$DIR/server/dist/seamain.js" "$@"
