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

if [[ ! -f ".env" ]]; then
  echo "ERROR: .env file not found."
  exit 1
fi

set -a
source .env
set +a

: "${APP_DIR:?APP_DIR missing in .env}"
: "${APP_NAME:?APP_NAME missing in .env}"
: "${PORT:?PORT missing in .env}"
: "${BIND:=127.0.0.1}"
: "${BUILD_DIR:=build}"

cd "$APP_DIR"

echo "[1/9] Ensure ecosystem.config.cjs"
cat > ecosystem.config.cjs <<EOC
module.exports = {
  apps: [
    {
      name: "${APP_NAME}",
      cwd: "${APP_DIR}",
      script: "npx",
      args: "serve -s ${BUILD_DIR} -l tcp://${BIND}:${PORT}",
      interpreter: "none",
      env: {
        NODE_ENV: "production"
      }
    }
  ]
};
EOC

echo "[2/9] Ensure start.sh"
cat > start.sh <<EOS
#!/usr/bin/env bash
set -euo pipefail

cd "${APP_DIR}"

if [[ ! -d "${BUILD_DIR}" ]]; then
  echo "ERROR: '${BUILD_DIR}/' not found."
  echo "Hint: run setup.sh first."
  exit 1
fi

if pm2 describe "${APP_NAME}" >/dev/null 2>&1; then
  pm2 reload ecosystem.config.cjs --only "${APP_NAME}"
else
  pm2 start ecosystem.config.cjs --only "${APP_NAME}"
fi

pm2 status "${APP_NAME}"
EOS

chmod +x start.sh

echo "[3/9] npm ci"
npm ci

echo "[4/9] build"
npm run build

echo "[5/9] ensure local serve"
if [[ ! -x "node_modules/.bin/serve" ]]; then
  npm i -D serve
fi

echo "[6/9] pm2 start/reload"
bash ./start.sh

echo "[7/9] pm2 save"
pm2 save --force

echo "[8/9] Checks"
pm2 status "${APP_NAME}"
ss -ltnp | grep ":${PORT}" || true
curl -I "http://${BIND}:${PORT}/" | head || true

echo "Setup complete for ${APP_NAME} on ${BIND}:${PORT}"
