#!/usr/bin/env sh
set -eu

ROOT_DIR="$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)"
OUT_FILE="$ROOT_DIR/internal/parser/vendors/pciids/pci.ids"
SUBMODULE_DIR="$ROOT_DIR/third_party/pciids"
SUBMODULE_FILE="$SUBMODULE_DIR/pci.ids"
BEST_EFFORT=0
SYNC_SUBMODULE=0

while [ $# -gt 0 ]; do
	case "$1" in
		--best-effort)
			BEST_EFFORT=1
			;;
		--sync-submodule)
			SYNC_SUBMODULE=1
			;;
		*)
			echo "error: unknown argument: $1" >&2
			exit 2
			;;
	esac
	shift
done

run_or_warn() {
	if "$@"; then
		return 0
	fi
	if [ "$BEST_EFFORT" -eq 1 ] && [ -f "$OUT_FILE" ]; then
		echo "warning: command failed: $*; keeping existing pci.ids" >&2
		exit 0
	fi
	return 1
}

if [ "$SYNC_SUBMODULE" -eq 1 ]; then
	run_or_warn git -C "$ROOT_DIR" submodule update --init --remote "$SUBMODULE_DIR"
fi

if [ ! -s "$SUBMODULE_FILE" ]; then
	if [ "$BEST_EFFORT" -eq 1 ] && [ -f "$OUT_FILE" ]; then
		echo "warning: missing submodule pci.ids; keeping existing file" >&2
		exit 0
	fi
	echo "error: missing $SUBMODULE_FILE (run: git submodule update --init --remote third_party/pciids)" >&2
	exit 1
fi

mkdir -p "$(dirname "$OUT_FILE")"

if [ -f "$OUT_FILE" ] && cmp -s "$SUBMODULE_FILE" "$OUT_FILE"; then
	echo "pci.ids is already up to date"
	exit 0
fi

cp "$SUBMODULE_FILE" "$OUT_FILE"
echo "updated $OUT_FILE from submodule $SUBMODULE_DIR"
