#!/bin/bash
# EasyComp Zeeland - ECZHOA/ECZQHOA servermigratie, versie 1.0.0.
# Zelfstandig script; geen download, Python of config-reset nodig.
set -eo pipefail
export LC_ALL=C
umask 077
EXPECTED_PLATFORM="Linux"

pause_window() {
    if [ "$(uname -s)" = "Darwin" ] && [ -t 0 ]; then
        printf '\nDruk op Enter om dit venster te sluiten...'
        read -r _ || true
    fi
}
if [ "$(uname -s)" != "$EXPECTED_PLATFORM" ]; then
    echo "Dit bestand is bedoeld voor $EXPECTED_PLATFORM."; pause_window; exit 1
fi
check=0
case "${1:-}" in
    --check) check=1; shift ;;
    --elevated) shift ;;
    "") ;;
    *) echo "Gebruik: bash \"$0\" [--check]"; exit 1 ;;
esac
target_home="${1:-$HOME}"
target_user="${2:-$(id -un)}"
target_config="${3:-${XDG_CONFIG_HOME:-$target_home/.config}}"
if [ "$(id -u)" -ne 0 ]; then
    echo 'Voor de serviceconfiguratie is het beheerderswachtwoord nodig.'
    if [ "$check" -eq 1 ]; then flag=--check; else flag=--elevated; fi
    rc=0
    sudo /bin/bash "$0" "$flag" "$target_home" "$target_user" "$target_config" || rc=$?
    pause_window
    exit "$rc"
fi
command -v perl >/dev/null || { echo 'Perl ontbreekt. Installeer Perl of neem contact op met EasyComp Zeeland.'; exit 1; }
stamp="$(date +%Y%m%d-%H%M%S)-$$"
tmp=''
stopped_units=()
stopped_user_units=()
stopped_plists=()
stopped_domains=()
target_uid="$(id -u "$target_user")"
user_systemctl() {
    sudo -u "$target_user" env XDG_RUNTIME_DIR="/run/user/$target_uid" \
        DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$target_uid/bus" systemctl --user "$@"
}
cleanup() {
    rc=$?
    trap - EXIT
    [ -z "$tmp" ] || rm -f "$tmp"
    for unit in "${stopped_units[@]}"; do
        if systemctl start "$unit"; then echo "Service weer gestart: $unit"
        else echo "Service niet herstart: $unit. Herstart de computer of neem contact op met EasyComp."; rc=1; fi
    done
    for unit in "${stopped_user_units[@]}"; do
        if user_systemctl start "$unit"; then echo "Gebruikersservice weer gestart: $unit"
        else echo "Gebruikersservice niet herstart: $unit."; rc=1; fi
    done
    i=0
    while [ "$i" -lt "${#stopped_plists[@]}" ]; do
        if launchctl bootstrap "${stopped_domains[$i]}" "${stopped_plists[$i]}"; then
            echo "Service weer geladen: ${stopped_plists[$i]}"
        else echo "Service niet herladen: ${stopped_plists[$i]}. Herstart de computer."; rc=1; fi
        i=$((i+1))
    done
    if [ "$rc" -ne 0 ]; then echo 'Herstel niet volledig uitgevoerd. Bewaar de melding voor EasyComp Zeeland.'; fi
    exit "$rc"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM

# Bewerk uitsluitend de vier netwerkvelden, geen ID/key/wachtwoorden.
# Raw bytes houden Unicode, regelafbrekingen en alle overige inhoud intact.
transform() {
    perl -0777 -pe '
      s{^((?:\xEF\xBB\xBF)?[ \t]*(?:rendezvous_server|custom-rendezvous-server|relay-server|api-server)[ \t]*=[ \t]*)(["\x27])([^"\x27\r\n]*)(\2[ \t]*(?:\#[^\r\n]*)?\r?$)}
       { my ($prefix,$quote,$value,$suffix)=($1,$2,$3,$4);
         $value =~ s{(?<![A-Za-z0-9_.-])hoa\.easycomp\.cloud(?![A-Za-z0-9_.-])}{hoa.easycompcloud.net}ig;
         $prefix.$quote.$value.$suffix;
       }egmx;
    ' "$1"
}
echo 'EasyComp Zeeland - ECZHOA verbindingsherstel'
echo 'Alleen hoa.easycomp.cloud wordt vervangen door hoa.easycompcloud.net.'
echo 'ID, key, 2FA, wachtwoorden en overige instellingen blijven behouden.'
shopt -s nullglob
files=()
if [ "$EXPECTED_PLATFORM" = "Darwin" ]; then
    bases=("$target_home/Library/Preferences" "/var/root/Library/Preferences" "/Library/Preferences")
else
    bases=("$target_config" "$target_home/.config" "/root/.config")
    for sandbox in "$target_home"/.var/app/*[Rr]ust[Dd]esk* "$target_home"/.var/app/*[Ee][Cc][Zz][Hh][Oo][Aa]* "$target_home"/.var/app/*[Ee][Cc][Zz][Qq][Hh][Oo][Aa]*; do
        [ ! -d "$sandbox/config" ] || bases+=("$sandbox/config")
    done
fi
for base in "${bases[@]}"; do
    [ -d "$base" ] || continue
    for dir in "$base"/*[Rr]ust[Dd]esk* "$base"/*[Ee][Cc][Zz][Hh][Oo][Aa]* "$base"/*[Ee][Cc][Zz][Qq][Hh][Oo][Aa]*; do
        [ -d "$dir" ] || continue
        for f in "$dir"/RustDesk2.toml "$dir"/ECZHOA2.toml "$dir"/ECZQHOA2.toml "$dir"/config/RustDesk2.toml "$dir"/config/ECZHOA2.toml "$dir"/config/ECZQHOA2.toml; do
            [ -f "$f" ] || continue
            if [ -L "$f" ]; then echo "Symbolische koppeling niet aangepast: $f"; exit 1; fi
            duplicate=0
            for existing in "${files[@]}"; do [ "$existing" != "$f" ] || duplicate=1; done
            [ "$duplicate" -eq 1 ] || files+=("$f")
        done
    done
done
pending=()
for f in "${files[@]}"; do
    tmp="$(mktemp "${f}.ecz-tmp.XXXXXX")"
    transform "$f" > "$tmp"
    if ! cmp -s "$f" "$tmp"; then pending+=("$f"); echo "Oud adres gevonden: $f"; fi
    rm -f "$tmp"; tmp=''
done
if [ "${#files[@]}" -eq 0 ]; then
    echo 'Geen bekende configuratie gevonden. Installeer/open de nieuwste ECZHOA of ECZQHOA.'
    echo 'Bij een bestaande installatie: laat EasyComp de configuratielocatie controleren.'
elif [ "${#pending[@]}" -eq 0 ]; then
    echo 'Geen oud serveradres gevonden in de bekende configuraties. Er is niets gewijzigd.'
elif [ "$check" -eq 1 ]; then
    echo "Controle: ${#pending[@]} bestand(en) kunnen worden aangepast. Er is niets gewijzigd."
else
    if [ "$EXPECTED_PLATFORM" = "Linux" ] && command -v systemctl >/dev/null; then
        while read -r unit rest; do
            case "$unit" in
                rustdesk.service|RustDesk.service|eczhoa.service|ECZHOA.service|eczqhoa.service|ECZQHOA.service)
                    if systemctl is-active --quiet "$unit"; then
                        stopped_units+=("$unit"); systemctl stop "$unit"
                    fi ;;
            esac
        done < <(systemctl list-unit-files --type=service --no-legend 2>/dev/null || true)
        if [ -S "/run/user/$target_uid/bus" ] && command -v sudo >/dev/null; then
            while read -r unit rest; do
                case "$unit" in
                    rustdesk.service|RustDesk.service|eczhoa.service|ECZHOA.service|eczqhoa.service|ECZQHOA.service)
                        if user_systemctl is-active --quiet "$unit"; then
                            stopped_user_units+=("$unit"); user_systemctl stop "$unit"
                        fi ;;
                esac
            done < <(user_systemctl list-unit-files --type=service --no-legend 2>/dev/null || true)
        fi
    elif [ "$EXPECTED_PLATFORM" = "Darwin" ]; then
        for directory in /Library/LaunchDaemons /Library/LaunchAgents "$target_home/Library/LaunchAgents"; do
            for plist in "$directory"/*[Rr]ust[Dd]esk*.plist "$directory"/*[Ee][Cc][Zz][Hh][Oo][Aa]*.plist "$directory"/*[Ee][Cc][Zz][Qq][Hh][Oo][Aa]*.plist; do
                label="$(/usr/libexec/PlistBuddy -c 'Print :Label' "$plist")"
                if [ "$directory" = "/Library/LaunchDaemons" ]; then domain=system; else domain="gui/$target_uid"; fi
                if launchctl print "$domain/$label" >/dev/null 2>&1; then
                    stopped_plists+=("$plist"); stopped_domains+=("$domain")
                    launchctl bootout "$domain/$label"
                fi
            done
        done
    fi
    pids=()
    while read -r pid comm; do
        name="${comm##*/}"
        case "$name" in
            rustdesk|RustDesk|ECZHOA|eczhoa|ECZQHOA|eczqhoa)
                [ "$pid" = "$$" ] || pids+=("$pid") ;;
        esac
    done < <(ps -axo pid=,comm=)
    for pid in "${pids[@]}"; do kill -TERM "$pid" 2>/dev/null || true; done
    for round in 1 2 3; do
        live=0
        for pid in "${pids[@]}"; do if kill -0 "$pid" 2>/dev/null; then live=1; fi; done
        [ "$live" -eq 1 ] || break
        sleep 1
    done
    for pid in "${pids[@]}"; do if kill -0 "$pid" 2>/dev/null; then kill -KILL "$pid"; fi; done
    changed=0
    for f in "${pending[@]}"; do
        tmp="$(mktemp "${f}.ecz-tmp.XXXXXX")"
        cp -p "$f" "$tmp"
        transform "$f" > "$tmp"
        if cmp -s "$f" "$tmp"; then rm -f "$tmp"; tmp=''; continue; fi
        backup="${f}.ecz-backup-${stamp}"
        [ ! -e "$backup" ] || { echo "Back-up bestaat al: $backup"; exit 1; }
        cp -p "$f" "$backup"
        mv -f "$tmp" "$f"; tmp=''
        tmp="$(mktemp "${f}.ecz-tmp.XXXXXX")"
        transform "$f" > "$tmp"
        cmp -s "$f" "$tmp" || { echo "Controle na schrijven mislukt: $f"; exit 1; }
        rm -f "$tmp"; tmp=''
        changed=$((changed+1))
        echo "Bijgewerkt: $f"
        echo "Back-up: $backup"
    done
    echo "Klaar: $changed configuratie(s) bijgewerkt."
fi
echo 'Open nu ECZHOA/ECZQHOA. Controleer Klaar voor verbinding en test een echte verbinding.'
