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

echo "[code-server] starting install"

# --------------------------------------------------
# Config
# --------------------------------------------------
ADDON_ROOT="/opt/zlh/addons/code-server"
ARTIFACT_DIR="/opt/zlh/addons/code-server"
MARKER="/opt/zlh/.zlh/addons/code-server.installed"

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

# --------------------------------------------------
# Idempotency
# --------------------------------------------------
if [ -f "${MARKER}" ]; then
  echo "[code-server] already installed"
  exit 0
fi

ARCHIVE="$(ls ${ARTIFACT_DIR}/code-server.* 2>/dev/null | head -n1)"
if [ -z "${ARCHIVE}" ]; then
  echo "[code-server][ERROR] artifact not found"
  exit 1
fi

echo "[code-server] extracting ${ARCHIVE}"
mkdir -p "${ADDON_ROOT}"

TMP_DIR="$(mktemp -d)"

case "${ARCHIVE}" in
  *.tar.gz)
    tar -xzf "${ARCHIVE}" -C "${TMP_DIR}"
    ;;
  *.zip)
    unzip -q "${ARCHIVE}" -d "${TMP_DIR}"
    ;;
  *)
    echo "[code-server][ERROR] unsupported archive format"
    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}"/* "${ADDON_ROOT}/"
rm -rf "${TMP_DIR}"

chmod +x "${ADDON_ROOT}/bin/code-server"

touch "${MARKER}"

echo "[code-server] install complete"
