#!/bin/zsh
set -e

CONTAINER_NAME="${CONTAINER_NAME:-zhctapp_v2_0}"

if ! docker ps --format '{{.Names}}' | grep -qx "${CONTAINER_NAME}"; then
  echo "容器 ${CONTAINER_NAME} 未运行，请先执行 zhctprompt/docker/start_zhct.sh"
  exit 1
fi

docker exec "${CONTAINER_NAME}" bash -lc '
set -e
export NVM_DIR=/usr/local/nvm
. "$NVM_DIR/nvm.sh"
nvm install 20
nvm use 20

stop_pid_tree() {
  local root_pid="$1"
  local child_pid

  if [ -z "$root_pid" ] || ! kill -0 "$root_pid" 2>/dev/null; then
    return 0
  fi

  for child_pid in $(pgrep -P "$root_pid" 2>/dev/null || true); do
    stop_pid_tree "$child_pid"
  done

  kill "$root_pid" 2>/dev/null || true
}

stop_pid() {
  local pid_file="$1"
  if [ -f "$pid_file" ]; then
    local pid
    pid="$(cat "$pid_file" 2>/dev/null || true)"
    if [ -n "$pid" ]; then
      stop_pid_tree "$pid"
      sleep 1
      if kill -0 "$pid" 2>/dev/null; then
        kill -9 "$pid" 2>/dev/null || true
      fi
    fi
    rm -f "$pid_file"
  fi
}

for f in \
  /tmp/store-static.pid /tmp/store-mobile.pid /tmp/store-screen.pid \
  /tmp/store20-static.pid /tmp/store20-mobile.pid /tmp/store20-screen.pid
do
  stop_pid "$f"
done

ensure_deps() {
  local dir="$1"
  cd "$dir"
  if [ ! -d node_modules ]; then
    npm install
  fi
}

ensure_deps /workspace/zhct/zhctproject/store20/public/static
nohup env HOST=0.0.0.0 PORT=8080 NODE_OPTIONS=--openssl-legacy-provider \
  npm run dev > /tmp/store20-static.log 2>&1 &
echo $! > /tmp/store20-static.pid
echo "store20/static -> :8080 pid=$(cat /tmp/store20-static.pid) log=/tmp/store20-static.log"

ensure_deps /workspace/zhct/zhctproject/store20/public/mobile
nohup env HOST=0.0.0.0 PORT=8081 NODE_OPTIONS="--openssl-legacy-provider --no-deprecation" \
  SASS_SILENCE_DEPRECATIONS=legacy-js-api,import \
  npx vue-cli-service serve > /tmp/store20-mobile.log 2>&1 &
echo $! > /tmp/store20-mobile.pid
echo "store20/mobile -> :8081 pid=$(cat /tmp/store20-mobile.pid) log=/tmp/store20-mobile.log"

ensure_deps /workspace/zhct/zhctproject/store20/public/screen
nohup env HOST=0.0.0.0 PORT=8082 NODE_OPTIONS="--openssl-legacy-provider --no-deprecation" \
  SASS_SILENCE_DEPRECATIONS=legacy-js-api,import \
  npm run dev > /tmp/store20-screen.log 2>&1 &
echo $! > /tmp/store20-screen.pid
echo "store20/screen -> :8082 pid=$(cat /tmp/store20-screen.pid) log=/tmp/store20-screen.log"
'

echo "store20(Node20) 三端启动命令已提交到容器。日志："
echo "  docker exec -it ${CONTAINER_NAME} bash -lc 'tail -f /tmp/store20-static.log'"
echo "  docker exec -it ${CONTAINER_NAME} bash -lc 'tail -f /tmp/store20-mobile.log'"
echo "  docker exec -it ${CONTAINER_NAME} bash -lc 'tail -f /tmp/store20-screen.log'"
