#!/bin/sh
# peak dependency installer + builder
# Checks and installs the system packages peak needs at runtime, then
# builds peak and copies the CEF runtime next to the binary.

set -e

BIN=/usr/bin
SRC="$(cd "$(dirname "$0")" && pwd)"

echo "== peak dependency check =="

missing=""
pkgcheck() {
    if ! pacman -Q "$1" >/dev/null 2>&1; then
        echo "Missing package: $1"
        missing="$missing $1"
    fi
}

pkgcheck xorg-server           # Xvfb
pkgcheck xorg-xkbcomp          # xkbcomp (Xvfb keymap compile)
pkgcheck xkeyboard-config      # keymaps for xkbcomp
pkgcheck jsoncpp               # cmake build dependency (libjsoncpp.so.2x)

# CEF runtime files that must live next to the binary
for f in libcef.so libEGL.so libGLESv2.so chrome-sandbox resources.pak \
         chrome_100_percent.pak chrome_200_percent.pak icudtl.dat; do
    if ! [ -e "$BIN/$f" ]; then
        echo "Missing runtime: $BIN/$f (copied during build)"
        missing="$missing <runtime>"
    fi
done

# SwiftShader / Vulkan transport
if ! ls "$BIN/libvk_swiftshader.so" "$BIN/libvulkan.so.1" >/dev/null 2>&1; then
    echo "Missing: SwiftShader Vulkan (libvk_swiftshader.so / libvulkan.so.1)"
    pacman -S --noconfirm --needed vulkan-radeon vulkan-intel || true
fi

if [ -n "$missing" ]; then
    echo "Installing missing packages:$missing"
    pacman -S --noconfirm --needed $missing || true
fi

echo "== Xvfb / xkbcomp check =="
if ! command -v Xvfb >/dev/null 2>&1; then
    echo "Xvfb missing; installing xorg-server"
    pacman -S --noconfirm --needed xorg-server
fi
if ! command -v xkbcomp >/dev/null 2>&1; then
    echo "xkbcomp missing; installing xorg-xkbcomp"
    pacman -S --noconfirm --needed xorg-xkbcomp
fi

echo "== build =="
if [ -d "$SRC/build" ]; then
    cd "$SRC"
    cmake --build build -j2
    echo "Build done. Binary at $BIN/peak"
else
    echo "No build dir; configure first:"
    echo "  cmake -S $SRC -B $SRC/build"
    exit 1
fi

echo "== done =="
echo "Run: peak [URL]"