#!/bin/sh
# apply-overlay.sh — Wild Dragon reskin patches applied to a freshly
# cloned datarhei/restreamer-ui tree. Two phases:
#
#   1. File overlay: rsync the contents of $OVERLAY/{public,src} on top
#      of the upstream working tree. Whole-file replacements only —
#      simple and idempotent.
#
#   2. Targeted in-place sed for one-line UI strings that aren't worth
#      a whole-file overlay (the header title, a few welcome strings).
#      Each pattern is anchored to a unique surrounding context so a
#      future upstream rename doesn't silently rewrite the wrong line.
#
# Caller: the Dockerfile's ui-builder stage. Expects:
#   $OVERLAY = /overlay   (the COPY destination)
#   $UI      = /ui        (the cloned upstream source root)
#
# Idempotent on a single source tree (rerunning is a no-op).

set -eu

OVERLAY="${OVERLAY:-/overlay}"
UI="${UI:-/ui}"

echo "wilddragon-overlay: layering $OVERLAY -> $UI"

# Phase 1 — file copies. -L follows any future symlinks, -p preserves
# perms, -R recursive. We deliberately avoid --delete: the upstream
# tree must stay intact except for the files we override.
for sub in public src; do
    if [ -d "$OVERLAY/$sub" ]; then
        cp -RLp "$OVERLAY/$sub/." "$UI/$sub/"
    fi
done

# Phase 2 — targeted seds. Each replacement is wrapped in a check so
# the script fails loudly if upstream changed the line we're patching
# (rather than silently no-op'ing and shipping un-rebranded UI).
patch_line() {
    file="$1"; needle="$2"; replacement="$3"
    if ! grep -qF "$needle" "$file"; then
        echo "wilddragon-overlay: ERROR — pattern not found in $file:"
        echo "  $needle"
        exit 1
    fi
    # Use awk for safe literal substitution (sed's regex would mishandle
    # special chars in the replacement).
    tmp="$(mktemp)"
    awk -v n="$needle" -v r="$replacement" '
        index($0, n) { sub(n, r); }
        { print }
    ' "$file" > "$tmp"
    mv "$tmp" "$file"
    echo "wilddragon-overlay: patched $(basename "$file") — $needle -> $replacement"
}

patch_line "$UI/src/Header.js" \
    '<Typography className="headerTitle">Restreamer</Typography>' \
    '<Typography className="headerTitle">Wild Dragon</Typography>'

# Welcome view top-of-page card.
patch_line "$UI/src/views/Welcome.js" \
    'title="Welcome to Restreamer v2"' \
    'title="Welcome to Wild Dragon"'

patch_line "$UI/src/views/Settings.js" \
    'title="Welcome to Restreamer v2"' \
    'title="Welcome to Wild Dragon"'

echo "wilddragon-overlay: done."
