#!/usr/bin/env bash
#
# Project- and workspace-specific setup, run as the devcontainer postCreateCommand.
# System-wide tooling (system packages, uv, gitleaks, actionlint, Claude Code,
# MCP Launchpad, gh, Homebrew + lazygit) is baked into the image — see
# .devcontainer/Dockerfile. Only steps that depend on the mounted workspace, plus
# the idempotent developer-CLI fallbacks below, belong here.

set -euo pipefail

cd /workspaces/qwikswitch-api

# Sync the project environment (runtime + dev dependency groups) from uv.lock.
uv sync

# Install the git pre-commit hooks into this checkout.
uv run pre-commit install

# Developer CLIs are baked into the image (see Dockerfile); re-install here only
# if missing — a cheap safety net for images/rebuilds where the baked copy isn't
# present. These blocks are idempotent no-ops when the tools already exist.

# gh — GitHub CLI (pinned standalone binary; keep GH_VERSION in sync with the Dockerfile).
if ! command -v gh >/dev/null 2>&1; then
    GH_VERSION=2.96.0
    curl -fsSL "https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz" \
        | sudo tar -xz -C /usr/local/bin --strip-components=2 "gh_${GH_VERSION}_linux_amd64/bin/gh"
    sudo chmod +x /usr/local/bin/gh
fi

# lazygit — terminal UI for git (via Homebrew), plus the system-wide shell wiring
# that keeps brew on PATH. Both are baked into the image (see Dockerfile); this
# restores them only if missing, so a stale image or a container whose home dir
# shadowed the baked ~/.bashrc still ends up with a working brew. Idempotent: a
# no-op once brew is on PATH and the snippets already exist.
BREW=/home/linuxbrew/.linuxbrew/bin/brew
if [ -x "$BREW" ]; then
    eval "$("$BREW" shellenv)"
    command -v lazygit >/dev/null 2>&1 || brew install lazygit

    # Restore the system-wide shellenv wiring if absent. Kept in sync with the
    # Dockerfile: profile.d (login), /etc/bash.bashrc (interactive non-login
    # bash), /etc/zsh/zshenv (zsh). System files need sudo (available here, as
    # for the gh fallback above).
    shellenv="eval \"\$($BREW shellenv)\""
    if [ ! -f /etc/profile.d/homebrew.sh ]; then
        printf '%s\n' "$shellenv" | sudo tee /etc/profile.d/homebrew.sh >/dev/null
    fi
    for rc in /etc/bash.bashrc /etc/zsh/zshenv; do
        if [ -f "$rc" ] && ! grep -qF 'brew shellenv' "$rc"; then
            printf '\n# Homebrew\n%s\n' "$shellenv" | sudo tee -a "$rc" >/dev/null
        fi
    done
fi
