#!/bin/sh
set -eu

SMITHAY_REPO="https://github.com/smithay/smithay"
SMITHAY_REV="0cd72d182a7f20daa13d48a14752c95130f0bef9"

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
VENDOR_DIR="$ROOT/vendor"
SMITHAY_DIR="$VENDOR_DIR/smithay"
PATCHES_DIR="$ROOT/patches"

mkdir -p "$VENDOR_DIR"

if [ ! -d "$SMITHAY_DIR/.git" ]; then
	echo "prepare-deps: bootstrapping smithay at $SMITHAY_REV"
	rm -rf "$SMITHAY_DIR"
	git init --quiet "$SMITHAY_DIR"
	cd "$SMITHAY_DIR"
	git remote add origin "$SMITHAY_REPO"
	git fetch --quiet --depth 1 origin "$SMITHAY_REV"
	git reset --quiet --hard FETCH_HEAD
else
	cd "$SMITHAY_DIR"
	if ! git rev-parse --quiet --verify "$SMITHAY_REV^{commit}" >/dev/null 2>&1; then
		git fetch --quiet --depth 1 origin "$SMITHAY_REV"
	fi
	git reset --quiet --hard "$SMITHAY_REV"
	git clean --quiet -fdx
fi

count=0
for patch in "$PATCHES_DIR"/smithay-*.patch; do
	[ -f "$patch" ] || continue
	echo "prepare-deps: applying $(basename "$patch")"
	git apply "$patch"
	count=$((count + 1))
done

echo "prepare-deps: smithay ready at $SMITHAY_REV ($count patch(es) applied)"
