#!/usr/bin/env bash
# .devcontainer/on-create.sh
# Runs as the devcontainer user (root) during onCreateCommand.
# Idempotent — safe to re-run.
set -euo pipefail

IS_CODESPACES="${CODESPACES:-}"

# ── 0. Ensure Docker is available early for lifecycle commands ───────────────
# Codespaces already provides Docker; avoid trying to start nested dockerd.
if ! command -v docker &>/dev/null; then
  if [ -n "$IS_CODESPACES" ]; then
    echo "WARNING: docker CLI is missing in Codespaces; skipping Docker bootstrap"
  else
    echo "→ Installing Docker CE..."
    curl -fsSL https://get.docker.com | sh
  fi
fi

if ! docker info &>/dev/null 2>&1; then
  if [ -n "$IS_CODESPACES" ]; then
    echo "WARNING: Docker daemon not reachable in Codespaces during on-create; continuing"
  elif command -v dockerd &>/dev/null; then
    echo "→ Starting dockerd..."
    dockerd \
      --host=unix:///var/run/docker.sock \
      --data-root=/var/lib/docker \
      >/tmp/dockerd.log 2>&1 &

    for i in $(seq 1 30); do
      docker info &>/dev/null 2>&1 && break
      sleep 1
    done

    if docker info &>/dev/null 2>&1; then
      echo "→ Docker daemon ready"
    else
      echo "WARNING: dockerd did not become ready within 30s (see /tmp/dockerd.log)"
    fi
  fi
fi

# ── 1. Initialize git submodules ──────────────────────────────────────────────
echo "→ Updating git submodules..."
git -C "$(dirname "$0")/.." submodule update --init --recursive \
  || echo "WARNING: submodule update failed (git credentials not yet available — re-run on-create.sh once the workspace is ready)"

# ── 2. Ensure zsh is installed ────────────────────────────────────────────────
if ! command -v zsh &>/dev/null; then
  echo "→ Installing zsh..."
  apt-get update -qq && apt-get install -y zsh
fi

# ── 2b. Ensure tmux is installed (apt, not nix, for host-OS integration) ─────
if ! command -v tmux &>/dev/null; then
  echo "→ Installing tmux..."
  apt-get update -qq && apt-get install -y tmux
fi

# ── 3. Configure nix to work without sandboxing ──────────────────────────────
# Most Docker environments (even privileged) can't run the nix build sandbox
# because they lack user-namespace support. Disabling sandbox + syscall filter
# allows nix/devbox to build and fetch packages normally.
mkdir -p /etc/nix
if [ ! -f /etc/nix/nix.conf ] || ! grep -q 'sandbox = false' /etc/nix/nix.conf; then
  cat >> /etc/nix/nix.conf <<'EOF'
sandbox = false
filter-syscalls = false
EOF
fi

# ── 4. Install nix (single-user, no daemon) if needed ────────────────────────
# The Determinate Systems installer handles Docker containers reliably.
if ! command -v nix &>/dev/null; then
  echo "→ Installing nix..."
  curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix \
    | sh -s -- install linux \
        --init none \
        --no-confirm \
        --extra-conf "sandbox = false" \
        --extra-conf "filter-syscalls = false"
fi

# Source the nix profile for the remainder of this script
if [ -f /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh ]; then
  # shellcheck disable=SC1091
  . /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh
fi

# ── 5. Start the nix daemon ──────────────────────────────────────────────────
# The Determinate Systems installer does not start the daemon automatically
# (--init none). We start it here for this shell, and rely on postStartCommand
# in devcontainer.json to restart it on subsequent workspace restarts.
/nix/var/nix/profiles/default/bin/nix-daemon --daemon &>/tmp/nix-daemon.log &
NIX_DAEMON_PID=$!
echo "→ nix-daemon started (pid $NIX_DAEMON_PID)"
sleep 3  # wait for the daemon socket to be ready

# ── 6. Install devbox if needed ───────────────────────────────────────────────
if ! command -v devbox &>/dev/null; then
  echo "→ Installing devbox..."
  curl -fsSL https://get.jetify.com/devbox | bash -s -- -f
fi

# ── 7. Install project packages ───────────────────────────────────────────────
echo "→ Running devbox install..."
devbox install

# ── 7b. Install pinned Supabase CLI (binary, not from nixpkgs) ───────────────
SUPABASE_CLI_VERSION="2.84.2"
SUPABASE_BIN="/usr/local/bin/supabase"
if [ -x "$SUPABASE_BIN" ] && "$SUPABASE_BIN" --version 2>/dev/null | grep -qF "$SUPABASE_CLI_VERSION"; then
  echo "→ Supabase CLI v${SUPABASE_CLI_VERSION} already installed"
else
  echo "→ Installing Supabase CLI v${SUPABASE_CLI_VERSION}..."
  ARCH="$(uname -m)"
  case "$ARCH" in
    x86_64)  ARCH_SUFFIX="linux_amd64" ;;
    aarch64) ARCH_SUFFIX="linux_arm64" ;;
    *)       echo "Unsupported architecture: $ARCH"; exit 1 ;;
  esac
  curl -fsSL "https://github.com/supabase/cli/releases/download/v${SUPABASE_CLI_VERSION}/supabase_${ARCH_SUFFIX}.tar.gz" \
    | tar xz -C /usr/local/bin supabase
  chmod +x "$SUPABASE_BIN"
  echo "→ Supabase CLI v${SUPABASE_CLI_VERSION} installed"
fi

# ── 8. Ensure shell init is set up for both bash and zsh ─────────────────────
add_to_shell() {
  local marker="$1" text="$2" file="$3"
  touch "$file"
  grep -qF "$marker" "$file" || printf '\n%s\n' "$text" >> "$file"
}

NIX_INIT='. /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh 2>/dev/null || true'
add_to_shell 'nix-daemon.sh' "$NIX_INIT" "$HOME/.bashrc"
add_to_shell 'nix-daemon.sh' "$NIX_INIT" "$HOME/.zshrc"

DEVBOX_PATH_INIT='export PATH="${HOME}/.local/share/devbox/global/default/.devbox/nix/profile/default/bin:${PATH}"'
add_to_shell 'devbox' "$DEVBOX_PATH_INIT" "$HOME/.zshrc"
add_to_shell 'devbox' "$DEVBOX_PATH_INIT" "$HOME/.bashrc"

echo "✓ on-create complete"
