#!/usr/bin/env bash
set -euo pipefail

# install.sh — overlays the WYSIWYG-default-value patch onto a SuiteCRM 8.x checkout.
# Usage:
#   1. Drop this whole folder at the target repo root (next to public/, dist/, etc.).
#   2. cd into the repo root and run:  ./wysiwyg_default_patch/install.sh
#      Or run from inside the folder:  ./install.sh
#   Flags:
#     --dry-run     show what would happen, change nothing
#     --target DIR  override the auto-detected repo root
#     --restore     restore the most recent backup made by this script

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"
PATCH_SRC="$SCRIPT_DIR/files"
BACKUP_ROOT="$SCRIPT_DIR/backups"

DRY_RUN=0
RESTORE=0
TARGET_ROOT=""

while [[ $# -gt 0 ]]; do
    case "$1" in
        --dry-run) DRY_RUN=1; shift ;;
        --restore) RESTORE=1; shift ;;
        --target)  TARGET_ROOT="$2"; shift 2 ;;
        -h|--help)
            sed -n '3,16p' "$0"; exit 0 ;;
        *) echo "unknown arg: $1" >&2; exit 2 ;;
    esac
done

# Resolve target root: explicit > parent of this folder if it looks like a repo > cwd
detect_root() {
    local candidate
    for candidate in "$TARGET_ROOT" "$SCRIPT_DIR/.." "$PWD"; do
        [[ -z "$candidate" ]] && continue
        candidate="$(cd "$candidate" 2>/dev/null && pwd || true)"
        [[ -z "$candidate" ]] && continue
        if [[ -d "$candidate/public/legacy/modules/DynamicFields/templates/Fields" ]]; then
            echo "$candidate"; return 0
        fi
    done
    return 1
}

if ! TARGET_ROOT="$(detect_root)"; then
    echo "ERROR: could not locate a SuiteCRM repo root." >&2
    echo "       Expected: <root>/public/legacy/modules/DynamicFields/templates/Fields/" >&2
    echo "       Pass --target /path/to/repo to override." >&2
    exit 1
fi

# Map: source file in files/  ->  destination path under TARGET_ROOT
declare -a MAPPING=(
    "TemplateWysiwyg.php|public/legacy/modules/DynamicFields/templates/Fields/TemplateWysiwyg.php"
    "wysiwyg.php|public/legacy/modules/DynamicFields/templates/Fields/Forms/wysiwyg.php"
    "wysiwyg.tpl|public/legacy/modules/DynamicFields/templates/Fields/Forms/wysiwyg.tpl"
)

# ----- restore mode -----
if [[ $RESTORE -eq 1 ]]; then
    if [[ ! -d "$BACKUP_ROOT" ]]; then
        echo "no backups directory found at $BACKUP_ROOT" >&2; exit 1
    fi
    LATEST="$(ls -1 "$BACKUP_ROOT" 2>/dev/null | sort | tail -n1 || true)"
    if [[ -z "$LATEST" ]]; then
        echo "no backups found in $BACKUP_ROOT" >&2; exit 1
    fi
    BDIR="$BACKUP_ROOT/$LATEST"
    echo "Restoring from backup: $BDIR"
    echo "Target root:           $TARGET_ROOT"
    for entry in "${MAPPING[@]}"; do
        IFS='|' read -r _ dst <<< "$entry"
        backup_file="$BDIR/$dst"
        if [[ -f "$backup_file" ]]; then
            if [[ $DRY_RUN -eq 1 ]]; then
                echo "  [dry-run] would restore: $dst"
            else
                cp -p "$backup_file" "$TARGET_ROOT/$dst"
                echo "  restored: $dst"
            fi
        else
            echo "  skip (no backup recorded): $dst"
        fi
    done
    echo "Done."
    exit 0
fi

# ----- install mode -----
TS="$(date +%Y%m%d-%H%M%S)"
BDIR="$BACKUP_ROOT/$TS"

echo "WYSIWYG default-value patch"
echo "  Patch source: $PATCH_SRC"
echo "  Target root:  $TARGET_ROOT"
echo "  Backup dir:   $BDIR"
[[ $DRY_RUN -eq 1 ]] && echo "  (DRY-RUN — no files will be written)"
echo

# Validate source files first
for entry in "${MAPPING[@]}"; do
    IFS='|' read -r src dst <<< "$entry"
    if [[ ! -f "$PATCH_SRC/$src" ]]; then
        echo "ERROR: missing source file: $PATCH_SRC/$src" >&2
        exit 1
    fi
done

# Validate destination dirs exist
for entry in "${MAPPING[@]}"; do
    IFS='|' read -r _ dst <<< "$entry"
    dst_dir="$(dirname "$TARGET_ROOT/$dst")"
    if [[ ! -d "$dst_dir" ]]; then
        echo "ERROR: destination directory missing: $dst_dir" >&2
        exit 1
    fi
done

for entry in "${MAPPING[@]}"; do
    IFS='|' read -r src dst <<< "$entry"
    src_path="$PATCH_SRC/$src"
    dst_path="$TARGET_ROOT/$dst"

    # Backup existing file (if any)
    if [[ -f "$dst_path" ]]; then
        if cmp -s "$src_path" "$dst_path"; then
            echo "  unchanged: $dst (already matches patch)"
            continue
        fi
        if [[ $DRY_RUN -eq 1 ]]; then
            echo "  [dry-run] would backup + overwrite: $dst"
        else
            mkdir -p "$BDIR/$(dirname "$dst")"
            cp -p "$dst_path" "$BDIR/$dst"
            cp -p "$src_path" "$dst_path"
            echo "  patched:   $dst   (backup: backups/$TS/$dst)"
        fi
    else
        if [[ $DRY_RUN -eq 1 ]]; then
            echo "  [dry-run] would create: $dst"
        else
            cp -p "$src_path" "$dst_path"
            echo "  created:   $dst   (no prior file — no backup)"
        fi
    fi
done

echo
echo "Done."
if [[ $DRY_RUN -eq 0 ]]; then
    echo "Next: open the target CRM and go to Admin > Repair > Quick Repair and Rebuild."
    echo "Rollback: ./install.sh --restore"
fi
