#!/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 use 14.21.3

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

start_app() {
  local dir="$1"
  local port="$2"
  local script="$3"
  local pid_file="$4"
  local log_file="$5"

  cd "$dir"
  if [ ! -d node_modules ]; then
    npm install
  fi
  nohup env HOST=0.0.0.0 PORT="$port" NODE_OPTIONS=--max_old_space_size=4096 \
    npm run "$script" > "$log_file" 2>&1 &
  echo $! > "$pid_file"
  echo "$dir -> :$port pid=$(cat "$pid_file") log=$log_file"
}

start_app /workspace/zhct/zhctproject/store/public/static 8080 dev /tmp/store-static.pid /tmp/store-static.log
start_app /workspace/zhct/zhctproject/store/public/mobile 8081 serve /tmp/store-mobile.pid /tmp/store-mobile.log
start_app /workspace/zhct/zhctproject/store/public/screen 8082 dev /tmp/store-screen.pid /tmp/store-screen.log
'

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