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

echo "[code-server] starting service"

SERVICE_ROOT="/opt/zlh/services/code-server"
MARKER="/opt/zlh/.zlh/addons/code-server.installed"
PID_FILE="/opt/zlh/.zlh/addons/code-server.pid"
LOG_FILE="/opt/zlh/logs/code-server.log"
WORKSPACE_DIR="${CODE_SERVER_WORKSPACE:-/home/dev/workspace}"
PORT="${CODE_SERVER_PORT:-6000}"
BIN="${SERVICE_ROOT}/bin/code-server"
CONFIG_DIR="/home/dev/.config/code-server"
CONFIG_FILE="${CONFIG_DIR}/config.yaml"

if [ ! -f "${MARKER}" ]; then
  echo "[code-server][ERROR] addon marker missing at ${MARKER}"
  exit 1
fi

if [ ! -x "${BIN}" ]; then
  echo "[code-server][ERROR] binary missing or not executable at ${BIN}"
  exit 1
fi

is_code_server_pid() {
  local pid="$1"
  if [ -z "${pid}" ] || [ ! -r "/proc/${pid}/cmdline" ]; then
    return 1
  fi
  local cmdline
  cmdline="$(tr '\000' ' ' < "/proc/${pid}/cmdline")"
  case "${cmdline}" in
    *code-server*"0.0.0.0:${PORT}"*) return 0 ;;
    *) return 1 ;;
  esac
}

find_running_pid() {
  local cmdline_path pid
  for cmdline_path in /proc/[0-9]*/cmdline; do
    pid="$(basename "$(dirname "${cmdline_path}")")"
    if is_code_server_pid "${pid}"; then
      echo "${pid}"
      return 0
    fi
  done
  return 1
}

mkdir -p "$(dirname "${PID_FILE}")"
mkdir -p "$(dirname "${LOG_FILE}")"
mkdir -p "${WORKSPACE_DIR}"
mkdir -p "${CONFIG_DIR}"
chown -R dev:dev "${WORKSPACE_DIR}" 2>/dev/null || true
touch "${LOG_FILE}"
chown dev:dev "${LOG_FILE}" 2>/dev/null || true
cat > "${CONFIG_FILE}" <<EOF
bind-addr: 0.0.0.0:${PORT}
auth: none
disable-telemetry: true
EOF
chown -R dev:dev "${CONFIG_DIR}" 2>/dev/null || true

if [ -f "${PID_FILE}" ] && is_code_server_pid "$(cat "${PID_FILE}")"; then
  echo "[code-server] already running"
  exit 0
fi

rm -f "${PID_FILE}"
echo "[code-server] action=service_launch command=\"${BIN} --bind-addr 0.0.0.0:${PORT} --auth none --disable-telemetry ${WORKSPACE_DIR}\""

if id dev >/dev/null 2>&1; then
  pid_tmp="${PID_FILE}.tmp"
  rm -f "${pid_tmp}"
  su -s /bin/sh dev -c "HOME=/home/dev USER=dev LOGNAME=dev nohup '${BIN}' --bind-addr '0.0.0.0:${PORT}' --auth none --disable-telemetry '${WORKSPACE_DIR}' >'${LOG_FILE}' 2>&1 & echo \$!" > "${pid_tmp}"
  mv "${pid_tmp}" "${PID_FILE}"
else
  HOME="/home/dev" USER="dev" LOGNAME="dev" \
    nohup "${BIN}" --bind-addr "0.0.0.0:${PORT}" --auth none --disable-telemetry "${WORKSPACE_DIR}" >"${LOG_FILE}" 2>&1 &
  echo $! > "${PID_FILE}"
fi

sleep 2
recorded_pid=""
if [ -f "${PID_FILE}" ]; then
  recorded_pid="$(cat "${PID_FILE}")"
fi
if ! is_code_server_pid "${recorded_pid}"; then
  discovered_pid="$(find_running_pid || true)"
  if [ -n "${discovered_pid}" ]; then
    echo "${discovered_pid}" > "${PID_FILE}"
  fi
fi

recorded_pid=""
if [ -f "${PID_FILE}" ]; then
  recorded_pid="$(cat "${PID_FILE}")"
fi
if ! is_code_server_pid "${recorded_pid}"; then
  echo "[code-server][ERROR] process exited after launch"
  if [ -f "${LOG_FILE}" ]; then
    tail -n 40 "${LOG_FILE}" || true
  fi
  rm -f "${PID_FILE}"
  exit 1
fi

echo "[code-server] action=service_launch status=ok pid=$(cat "${PID_FILE}")"
