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

echo "[code-server] starting install"

# ----------------------------------------------------------
# Config
# ----------------------------------------------------------
SERVICE_ROOT="/opt/zlh/services/code-server"
ZLH_ARTIFACT_BASE_URL="${ZLH_ARTIFACT_BASE_URL:-http://zlh-artifacts.internal.zlh:8080}"
ARTIFACT_NAME="${ZLH_CODESERVER_ARTIFACT:-code-server.tar.gz}"
ARTIFACT_URL="${ZLH_ARTIFACT_BASE_URL%/}/addons/code-server/${ARTIFACT_NAME}"
ARTIFACT_TMP="/tmp/${ARTIFACT_NAME}"
MARKER="/opt/zlh/.zlh/addons/code-server.installed"
WORKSPACE_DIR="${CODE_SERVER_WORKSPACE:-/home/dev/workspace}"
PORT="${CODE_SERVER_PORT:-6000}"
BIN="${SERVICE_ROOT}/bin/code-server"
LINK_PATH="/usr/local/bin/code-server"
CONFIG_DIR="/home/dev/.config/code-server"
CONFIG_FILE="${CONFIG_DIR}/config.yaml"

mkdir -p "$(dirname "${MARKER}")"

download_artifact() {
  echo "[code-server] action=artifact_fetch step=download url=${ARTIFACT_URL} target=${ARTIFACT_TMP}"
  if command -v curl >/dev/null 2>&1; then
    curl -fL "${ARTIFACT_URL}" -o "${ARTIFACT_TMP}"
  elif command -v wget >/dev/null 2>&1; then
    wget -O "${ARTIFACT_TMP}" "${ARTIFACT_URL}"
  else
    echo "[code-server][ERROR] curl or wget is required"
    exit 1
  fi
  echo "[code-server] action=artifact_fetch step=download status=ok url=${ARTIFACT_URL} target=${ARTIFACT_TMP}"
}

extract_artifact() {
  local tmp_dir
  tmp_dir="$(mktemp -d)"
  echo "[code-server] action=artifact_extract step=extract source=${ARTIFACT_TMP} target=${SERVICE_ROOT}"

  case "${ARTIFACT_NAME}" in
    *.tar.gz|*.tgz)
      tar -xzf "${ARTIFACT_TMP}" -C "${tmp_dir}"
      ;;
    *.zip)
      if command -v unzip >/dev/null 2>&1; then
        unzip -q "${ARTIFACT_TMP}" -d "${tmp_dir}"
      elif command -v bsdtar >/dev/null 2>&1; then
        bsdtar -xf "${ARTIFACT_TMP}" -C "${tmp_dir}"
      else
        echo "[code-server][ERROR] unzip or bsdtar is required for zip artifacts"
        exit 127
      fi
      ;;
    *)
      echo "[code-server][ERROR] unsupported artifact format: ${ARTIFACT_NAME}"
      exit 1
      ;;
  esac

  EXTRACTED_DIR="$(find "${tmp_dir}" -maxdepth 1 -type d -name 'code-server*' | head -n1)"
  if [ -z "${EXTRACTED_DIR}" ]; then
    echo "[code-server][ERROR] failed to locate extracted directory"
    exit 1
  fi

  mv "${EXTRACTED_DIR}"/* "${SERVICE_ROOT}/"
  rm -rf "${tmp_dir}"
  echo "[code-server] action=artifact_extract step=extract status=ok source=${ARTIFACT_TMP} target=${SERVICE_ROOT}"
}

validate_artifact_shape() {
  if [ ! -f "${BIN}" ]; then
    echo "[code-server][ERROR] artifact missing expected binary path ${BIN}; expected a runnable release archive, got an incompatible archive"
    exit 1
  fi
}

write_config() {
  mkdir -p "${CONFIG_DIR}"
  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
  echo "[code-server] action=config_write path=${CONFIG_FILE} status=ok"
}

# ----------------------------------------------------------
# Idempotency
# ----------------------------------------------------------
if [ ! -x "${BIN}" ]; then
  echo "[code-server] action=artifact_install target=${SERVICE_ROOT} status=begin"
  download_artifact
  rm -rf "${SERVICE_ROOT}"
  mkdir -p "${SERVICE_ROOT}"
  extract_artifact
  validate_artifact_shape
  chmod +x "${BIN}"
  ln -sfn "${BIN}" "${LINK_PATH}"
fi

mkdir -p "${WORKSPACE_DIR}"
write_config

touch "${MARKER}"
rm -f "${ARTIFACT_TMP}"

echo "[code-server] action=artifact_install target=${SERVICE_ROOT} status=ok"
