#!/bin/bash
# Rebuild custom UI files using patches
#   install.sh          — apply patches to uifiles/isuldor/
#   install.sh --update — regenerate *.diff from uifiles/isuldor/ (CRLF-normalized)
#
# Set EQ_GAME_PATH to your install root, or rely on auto-detection.

set -euo pipefail

UI_NAME=isuldor
SCRIPT_PATH=$(dirname "${0}")
# shellcheck source=eq-path.sh
source "${SCRIPT_PATH}/eq-path.sh"

GAME_PATH=$(resolve_game_path) || exit 1
UI_FOLDER="${GAME_PATH}/uifiles/${UI_NAME}"
DEFAULT_UI="${GAME_PATH}/uifiles/default"

# Stock uifiles/default/*.xml use CRLF; LF-only isuldor files produce whole-file diffs.
crlf_temp() {
    local src=$1
    local dest=$2
    sed 's/$/\r/' "${src}" > "${dest}"
}

needs_crlf_diff() {
    local default_xml=$1
    file "${default_xml}" 2>/dev/null | grep -q CRLF
}

# Regenerate patch set from built skin
if [[ "${1:-}" == "-u" || "${1:-}" == "--update" ]]; then
    echo "Updating patch set from ${UI_FOLDER}..."
    UI_FILES=( $( find "${UI_FOLDER}" -name '*.xml' -exec basename {} .xml \; ))
    for UI_FILE in "${UI_FILES[@]}"; do
        default_xml="${DEFAULT_UI}/${UI_FILE}.xml"
        isuldor_xml="${UI_FOLDER}/${UI_FILE}.xml"
        out_diff="${SCRIPT_PATH}/${UI_FILE}.diff"
        if needs_crlf_diff "${default_xml}"; then
            crlf_temp "${isuldor_xml}" "${out_diff}.isuldor.crlf"
            diff -u "${default_xml}" "${out_diff}.isuldor.crlf" > "${out_diff}"
            rm -f "${out_diff}.isuldor.crlf"
        else
            diff -u "${default_xml}" "${isuldor_xml}" > "${out_diff}"
        fi
        echo "  ${UI_FILE}.diff"
    done
    echo "Run: bash ui/verify.sh --record"
    exit 0
fi

mkdir -vp "${UI_FOLDER}"
cp "${SCRIPT_PATH}"/*.tga "${UI_FOLDER}/"

UI_FILES=( $( find "${SCRIPT_PATH}" -name '*.diff' -exec basename {} .diff \; ))

for UI_FILE in "${UI_FILES[@]}"; do
    if ! patch --ignore-whitespace --fuzz 3 -o "${UI_FOLDER}/${UI_FILE}.xml" \
        "${DEFAULT_UI}/${UI_FILE}.xml" < "${SCRIPT_PATH}/${UI_FILE}.diff"; then
        echo "Error: patch failed for ${UI_FILE}" >&2
        exit 1
    fi
done

echo "Installed ${#UI_FILES[@]} files to ${UI_FOLDER}"
echo "Set UISkin=${UI_NAME} in your character UI INI, then: bash ui/verify.sh --record"
