#!/bin/bash
#
# ResetBrowserLocal.sh - interactive browser reset for this Mac.
#
# Walks you through: pick a browser > back up bookmarks and passwords > close the browser >
# check the exports are in Documents > rename its data folder(s) to '.bak' > relaunch it >
# restore your bookmarks and passwords > optionally revert to the old profile > summary.
# Nothing is deleted. Reverting renames the new profile to '.tmp' and the '.bak' back.
#
# Usage: bash ResetBrowserLocal.sh   (from Terminal, in the folder you saved it to)

set -u

BOLD=$'\033[1m'; DIM=$'\033[2m'; RED=$'\033[31m'; GREEN=$'\033[32m'; YELLOW=$'\033[33m'; CYAN=$'\033[36m'; RESET=$'\033[0m'
SUFFIX=".bak"
TMP_SUFFIX=".tmp"
CLOSE_TIMEOUT_SEC=20
BROWSERS="edge chrome firefox safari"

# ───────────────────────────────────────────────────────────────────────────────────── browser info
display_name() {
    case "$1" in
        edge) echo "Microsoft Edge" ;; chrome) echo "Google Chrome" ;;
        firefox) echo "Mozilla Firefox" ;; safari) echo "Safari" ;;
    esac
}

app_name() {   # name used by 'open -a' and AppleScript
    case "$1" in
        edge) echo "Microsoft Edge" ;; chrome) echo "Google Chrome" ;;
        firefox) echo "Firefox" ;; safari) echo "Safari" ;;
    esac
}

process_name() {
    case "$1" in
        edge) echo "Microsoft Edge" ;; chrome) echo "Google Chrome" ;;
        firefox) echo "firefox" ;; safari) echo "Safari" ;;
    esac
}

data_paths() {   # profile folder first, then caches
    case "$1" in
        edge)
            echo "$HOME/Library/Application Support/Microsoft Edge"
            echo "$HOME/Library/Caches/Microsoft Edge" ;;
        chrome)
            echo "$HOME/Library/Application Support/Google/Chrome"
            echo "$HOME/Library/Caches/Google/Chrome" ;;
        firefox)
            echo "$HOME/Library/Application Support/Firefox"
            echo "$HOME/Library/Caches/Firefox" ;;
        safari)
            echo "$HOME/Library/Safari"
            echo "$HOME/Library/Containers/com.apple.Safari"
            echo "$HOME/Library/Caches/com.apple.Safari"
            echo "$HOME/Library/Preferences/com.apple.Safari.plist" ;;
    esac
}

# Browser pages used in the steps: "label|address". They are opened with 'open -a <browser>',
# because macOS has no handler for chrome://, edge:// or about: addresses when clicked in Terminal.
backup_links() {
    case "$1" in
        edge)    echo "Favorites|edge://favorites"; echo "Passwords|edge://settings/autofill/passwords" ;;
        chrome)  echo "Bookmarks|chrome://bookmarks"; echo "Passwords|chrome://password-manager/settings" ;;
        firefox) echo "Passwords|about:logins" ;;
    esac
}

restore_links() {
    case "$1" in
        edge)    echo "Favorites|edge://favorites"; echo "Passwords|edge://settings/autofill/passwords" ;;
        chrome)  echo "Bookmarks|chrome://bookmarks"; echo "Passwords|chrome://password-manager/settings" ;;
        firefox) echo "Passwords|about:logins" ;;
    esac
}

is_installed() { open -Ra "$(app_name "$1")" >/dev/null 2>&1; }
is_running()   { pgrep -x -U "$(id -u)" "$(process_name "$1")" >/dev/null 2>&1; }
has_data()     { [[ -e "$(data_paths "$1" | head -n 1)" ]]; }

backup_steps() {
    case "$1" in
        edge) cat <<'EOF'
  Favorites: open edge://favorites > More options (...) > Export favorites
             Save the .html file to Documents.
  Passwords: open edge://settings/autofill/passwords > (...) > Export passwords
             Save the .csv file to Documents.
EOF
        ;;
        chrome) cat <<'EOF'
  Bookmarks: open chrome://bookmarks > three dots (top right) > Export bookmarks
             Save the .html file to Documents.
  Passwords: open chrome://password-manager/settings > Export passwords > Download file
             Save the .csv file to Documents.
EOF
        ;;
        firefox) cat <<'EOF'
  Bookmarks: Cmd+Shift+O > Import and Backup > Export Bookmarks to HTML
             Save the .html file to Documents.
  Passwords: open about:logins > three dots (...) > Export Passwords
             Save the .csv file to Documents.
EOF
        ;;
        safari) cat <<'EOF'
  Bookmarks: File > Export > Bookmarks. Save the .html file to Documents.
  Passwords: Safari passwords live in the Passwords app / Keychain and are NOT touched
             by this reset. To keep a copy anyway: Passwords app > File > Export All Passwords.
  Note:      Reading List and history can't be exported and will be lost.
EOF
        ;;
    esac
}

restore_steps() {
    case "$1" in
        edge) cat <<'EOF'
  1. Favorites: open edge://favorites > More options (...) > Import favorites
     > "Favorites or bookmarks HTML file" > choose your .html file.
  2. Passwords: open edge://settings/autofill/passwords > (...) > Import passwords
     > choose your .csv file.
EOF
        ;;
        chrome) cat <<'EOF'
  1. Bookmarks: open chrome://bookmarks > three dots (top right) > Import bookmarks
     > choose your .html file (they appear in an "Imported" folder).
  2. Passwords: open chrome://password-manager/settings > Import passwords > Select file
     > choose your .csv file.
EOF
        ;;
        firefox) cat <<'EOF'
  1. Bookmarks: Cmd+Shift+O > Import and Backup > Import Bookmarks from HTML
     > choose your .html file.
  2. Passwords: open about:logins > three dots (...) > Import from a File > choose your .csv file.
EOF
        ;;
        safari) cat <<'EOF'
  1. Bookmarks: File > Import From > Bookmarks HTML File > choose your .html file.
  2. Passwords: nothing to do - they are still in the Passwords app / Keychain.
EOF
        ;;
    esac
}

# ────────────────────────────────────────────────────────────────────────────────────────── helpers
header() { printf '\n%s== %s ==%s\n\n' "$BOLD$CYAN" "$1" "$RESET"; }

confirm() {   # confirm "question" -> 0 for yes
    local answer
    while true; do
        read -r -p "$1 [y/n]: " answer || exit 1
        case "$(printf '%s' "$answer" | tr '[:upper:]' '[:lower:]')" in
            y|yes) return 0 ;;
            n|no) return 1 ;;
        esac
    done
}

abort() { printf '\n%sStopped: %s%s\nNothing was changed.\n' "$YELLOW" "$1" "$RESET"; exit 0; }

free_name() {   # free_name <path> <suffix>: never overwrites an existing folder
    if [[ ! -e "$1$2" ]]; then echo "$1$2"; else echo "$1$2.$(date '+%Y%m%d-%H%M%S')"; fi
}
backup_name() { free_name "$1" "$SUFFIX"; }

export_folders() {   # Documents, plus OneDrive's Documents if it is a different folder
    local d real seen=""
    for d in "$HOME/Documents" "$HOME"/Library/CloudStorage/OneDrive*/Documents; do
        [[ -d "$d" ]] || continue
        real=$(cd -P "$d" 2>/dev/null && pwd)
        [[ "$seen" == *"|$real|"* ]] && continue
        seen="$seen|$real|"
        echo "$d"
    done
}

export_names() {   # export_names <bookmarks|passwords>: today's default export file name(s) for the browser
    local unpadded padded
    unpadded="$(date '+%-m_%-d_%y')"   # e.g. 11_20_26 (single-digit months/days have no leading zero)
    padded="$(date '+%m_%d_%y')"
    case "$BROWSER:$1" in
        chrome:bookmarks)  echo "bookmarks_$unpadded.html"; echo "bookmarks_$padded.html" ;;
        chrome:passwords)  echo "Chrome Passwords.csv" ;;
        edge:bookmarks)    echo "favorites_$unpadded.html"; echo "favorites_$padded.html" ;;
        edge:passwords)    echo "Microsoft Edge Passwords.csv" ;;
        firefox:bookmarks) echo "bookmarks.html" ;;
        firefox:passwords) echo "logins.csv" ;;
        safari:bookmarks)  echo "Safari Bookmarks.html" ;;
    esac
}

file_date() { stat -f '%Sm' -t '%Y-%m-%d' "$1" 2>/dev/null; }   # last saved, local time

find_exports() {   # find_exports <bookmarks|passwords>: files directly in Documents (no subfolders) saved today
    local dir name today
    today=$(date '+%Y-%m-%d')
    STALE_EXPORTS=""
    while IFS= read -r dir; do
        while IFS= read -r name; do
            [[ -n "$name" && -f "$dir/$name" ]] || continue
            if [[ "$(file_date "$dir/$name")" == "$today" ]]; then
                echo "$dir/$name"
            else
                STALE_EXPORTS="$STALE_EXPORTS$dir/$name (saved $(file_date "$dir/$name"))"$'\n'
            fi
        done <<< "$(export_names "$1" | sort -u)"
    done <<< "$(export_folders)"
}

size_kb() {   # total size in KB of the given paths (missing paths count as 0)
    local total=0 p kb
    for p in "$@"; do
        [[ -e "$p" ]] || continue
        kb=$(du -sk "$p" 2>/dev/null | awk '{print $1}')
        total=$((total + ${kb:-0}))
    done
    echo "$total"
}

human() {   # KB -> readable size
    awk -v k="$1" 'BEGIN { if (k >= 1048576) printf "%.2f GB", k/1048576;
                           else if (k >= 1024) printf "%.1f MB", k/1024; else printf "%d KB", k }'
}

open_links() {   # offers the browser pages from a links function as numbered choices
    local func="$1" lines=() line i choice
    while IFS= read -r line; do [[ -n "$line" ]] && lines+=("$line"); done <<< "$("$func" "$BROWSER")"
    [[ ${#lines[@]} -eq 0 ]] && return
    echo
    echo "${BOLD}Open a page in $NAME:${RESET}"
    for i in "${!lines[@]}"; do
        printf '  %s%d)%s %-11s %s%s%s\n' "$BOLD" $((i + 1)) "$RESET" "${lines[$i]%%|*}" "$CYAN" "${lines[$i]#*|}" "$RESET"
    done
    while true; do
        read -r -p "Number to open it, or Return to continue: " choice || exit 1
        [[ -z "$choice" ]] && return
        if [[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= ${#lines[@]} )); then
            open -a "$(app_name "$BROWSER")" "${lines[$((choice - 1))]#*|}" 2>/dev/null \
                || printf '%sCould not open it - type the address in %s instead.%s\n' "$YELLOW" "$NAME" "$RESET"
        fi
    done
}

quit_browser() {
    local key="$1" waited=0
    osascript -e "tell application \"$(app_name "$key")\" to quit" >/dev/null 2>&1
    printf 'Waiting for %s to quit' "$(display_name "$key")"
    while (( waited < CLOSE_TIMEOUT_SEC )); do
        is_running "$key" || { printf ' %sdone%s\n' "$GREEN" "$RESET"; return 0; }
        printf '.'; sleep 1; waited=$((waited + 1))
    done
    printf '\n%s%s did not quit (it may be showing a "leave page?" dialog).%s\n' "$YELLOW" "$(display_name "$key")" "$RESET"
    confirm "Force quit it? Unsaved work in open tabs will be lost" || return 1
    pkill -x -U "$(id -u)" "$(process_name "$key")"; sleep 2
    is_running "$key" && { pkill -9 -x -U "$(id -u)" "$(process_name "$key")"; sleep 2; }
    ! is_running "$key"
}

# ──────────────────────────────────────────────────────────────────────────────────────────── steps
choose_browser() {
    header "Reset a browser"
    local keys=() key i=1 state choice
    for key in $BROWSERS; do
        if ! is_installed "$key"; then
            state="${DIM}not installed${RESET}"
        elif ! has_data "$key"; then
            state="${DIM}installed, no profile data yet${RESET}"
        elif is_running "$key"; then
            state="${GREEN}running${RESET}"
        else
            state="not running"
        fi
        printf '  %d) %-16s %s\n' "$i" "$(display_name "$key")" "$state"
        keys+=("$key"); i=$((i + 1))
    done
    printf '  q) Quit\n\n'
    while true; do
        read -r -p "Which browser are you having issues with? " choice || exit 1
        [[ "$choice" == [qQ] ]] && abort "cancelled."
        if [[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= ${#keys[@]} )); then
            key="${keys[$((choice - 1))]}"
            if ! is_installed "$key"; then
                echo "$(display_name "$key") is not installed on this Mac. Pick another browser."
            elif ! has_data "$key"; then
                echo "$(display_name "$key") has no profile data yet, so there is nothing to reset. Pick another browser."
            else
                BROWSER="$key"; NAME=$(display_name "$key"); return
            fi
            continue
        fi
        echo "Enter a number from 1 to ${#keys[@]}, or q."
    done
}

backup_prompt() {
    header "Step 1 of 4: Back up $NAME"
    if is_running "$BROWSER"; then
        printf '%s%s is running%s - good, you need it open to export.\n\n' "$GREEN" "$NAME" "$RESET"
    else
        printf '%s%s is not running.%s Opening it so you can export...\n\n' "$YELLOW" "$NAME" "$RESET"
        open -a "$(app_name "$BROWSER")" 2>/dev/null
    fi
    backup_steps "$BROWSER"
    printf '\n%sPassword .csv files are not encrypted - delete them after you re-import.%s\n' "$DIM" "$RESET"
    open_links backup_links
    echo
    confirm "Have you exported your bookmarks and passwords?" \
        || abort "export your bookmarks and passwords first, then run this again."
    check_exports
}

check_exports() {
    header "Checking your exports"
    local bookmarks passwords missing=()
    echo "Looking in Documents for these files saved today ($(date '+%Y-%m-%d')):"
    export_names bookmarks | sort -u | sed 's/^/    /'
    [[ "$BROWSER" != "safari" ]] && export_names passwords | sed 's/^/    /'
    echo
    local stale=""
    find_exports bookmarks > /tmp/.rbl_$$; bookmarks=$(cat /tmp/.rbl_$$); stale="$STALE_EXPORTS"
    if [[ "$BROWSER" != "safari" ]]; then
        find_exports passwords > /tmp/.rbl_$$; passwords=$(cat /tmp/.rbl_$$); stale="$stale$STALE_EXPORTS"
    fi
    rm -f /tmp/.rbl_$$
    if [[ -n "$bookmarks" ]]; then
        printf '  %sBookmarks found:%s\n' "$GREEN" "$RESET"; printf '%s\n' "$bookmarks" | sed 's/^/    /'
    else
        missing+=("bookmarks ($(export_names bookmarks | head -n 1))")
    fi
    if [[ "$BROWSER" == "safari" ]]; then
        echo "  Passwords: not needed for Safari (they stay in the Passwords app)."
    elif [[ -n "$passwords" ]]; then
        printf '  %sPasswords found:%s\n' "$GREEN" "$RESET"; printf '%s\n' "$passwords" | sed 's/^/    /'
    else
        missing+=("passwords ($(export_names passwords | head -n 1))")
    fi
    if (( ${#missing[@]} > 0 )); then
        printf '\n%sNo backup made today was found in Documents for: %s%s\n' "$YELLOW" "$(IFS=,; echo "${missing[*]}" | sed 's/,/, /g')" "$RESET"
        if [[ -n "$stale" ]]; then
            echo "These older exports were found, but they may be missing recent changes:"
            printf '%s' "$stale" | sed 's/^/    /'
        fi
        echo "Please make fresh backups now using the steps above, saved to Documents, then answer below."
        open_links backup_links
        echo
        confirm "Did you make fresh backups today (in Documents or somewhere else)?" \
            || abort "make fresh backups of your bookmarks and passwords, then run this again."
    fi
}

# Earlier backups of this browser: one line per backup set, as "<suffix>|<date>|<size KB>".
# A set is every data path with the same ending, e.g. ".bak" or ".bak.20261119-101500".
earlier_backups() {
    local primary suffix b paths p kb
    primary=$(data_paths "$BROWSER" | head -n 1)
    for b in "$primary$SUFFIX" "$primary$SUFFIX".*; do
        [[ -e "$b" ]] || continue
        suffix="${b#"$primary"}"
        kb=0
        while IFS= read -r p; do kb=$((kb + $(size_kb "$p$suffix"))); done <<< "$(data_paths "$BROWSER")"
        printf '%s|%s|%s\n' "$suffix" "$(stat -f '%Sm' -t '%Y-%m-%d %H:%M' "$b")" "$kb"
    done
}

trash() {   # moves a path to the Trash through Finder, so it can still be put back
    osascript -e "tell application \"Finder\" to delete (POSIX file \"$1\" as alias)" >/dev/null 2>&1
}

handle_earlier_backups() {
    local sets=() line i choice suffix p
    while IFS= read -r line; do [[ -n "$line" ]] && sets+=("$line"); done <<< "$(earlier_backups)"
    (( ${#sets[@]} == 0 )) && return
    header "Earlier $NAME backups found"
    echo "A previous run already backed up $NAME:"
    for i in "${!sets[@]}"; do
        IFS='|' read -r suffix line p <<< "${sets[$i]}"
        printf '  %d) %-28s %s  %s(%s)%s\n' $((i + 1)) "${suffix}" "$line" "$DIM" "$(human "$p")" "$RESET"
    done
    cat <<EOF

What do you want to do?
  k) Keep them, and save this reset's backup under a new dated name (recommended)
  t) Move them to the Trash first (they can still be put back from the Trash)
  r) Don't reset - restore one of these earlier backups instead
  q) Cancel
EOF
    while true; do
        read -r -p "Choose k, t, r or q: " choice || exit 1
        case "$choice" in
            [kK]) return ;;
            [qQ]) abort "cancelled." ;;
            [tT])
                confirm "Move ${#sets[@]} earlier backup set(s) of $NAME to the Trash?" || continue
                for i in "${!sets[@]}"; do
                    suffix="${sets[$i]%%|*}"
                    while IFS= read -r p; do
                        [[ -e "$p$suffix" ]] || continue
                        if trash "$p$suffix"; then
                            printf '  %strashed%s  %s\n' "$GREEN" "$RESET" "$p$suffix"
                        else
                            printf '  %sCould not trash %s - it was left in place.%s\n' "$YELLOW" "$p$suffix" "$RESET"
                        fi
                    done <<< "$(data_paths "$BROWSER")"
                done
                return ;;
            [rR])
                if (( ${#sets[@]} == 1 )); then i=0; else
                    while true; do
                        read -r -p "Restore which backup (1-${#sets[@]})? " i || exit 1
                        [[ "$i" =~ ^[0-9]+$ ]] && (( i >= 1 && i <= ${#sets[@]} )) && { i=$((i - 1)); break; }
                    done
                fi
                restore_earlier "${sets[$i]%%|*}"
                exit 0 ;;
        esac
    done
}

restore_earlier() {   # restore_earlier <suffix>: current profile -> .tmp, backup -> original
    local suffix="$1" p tmp
    echo
    echo "The current $NAME profile will be renamed to '$TMP_SUFFIX' and the"
    echo "'$suffix' backup put back in its place."
    confirm "Close $NAME and restore it now?" || abort "cancelled."
    if is_running "$BROWSER"; then quit_browser "$BROWSER" || abort "$NAME is still running."; fi
    sleep 1
    while IFS= read -r p; do
        [[ -e "$p$suffix" ]] || continue
        if [[ -e "$p" ]]; then
            tmp=$(free_name "$p" "$TMP_SUFFIX")
            mv "$p" "$tmp" 2>/dev/null || { printf '%sCould not rename %s. Stopped here.%s\n' "$RED" "$p" "$RESET"; exit 1; }
            printf '  %sok%s  %s\n      -> %s\n' "$GREEN" "$RESET" "$p" "$tmp"
        fi
        mv "$p$suffix" "$p" 2>/dev/null || { printf '%sCould not restore %s. Stopped here.%s\n' "$RED" "$p$suffix" "$RESET"; exit 1; }
        printf '  %sok%s  %s\n      -> %s\n' "$GREEN" "$RESET" "$p$suffix" "$p"
    done <<< "$(data_paths "$BROWSER")"
    [[ "$BROWSER" == "safari" ]] && killall -u "$(id -un)" cfprefsd >/dev/null 2>&1
    printf '\n%s%s has been restored.%s Relaunching...\n' "$GREEN" "$NAME" "$RESET"
    open -a "$(app_name "$BROWSER")" 2>/dev/null
}

impact_prompt() {
    header "Step 2 of 4: What the reset does"
    cat <<EOF
$NAME will start fresh.

${BOLD}Can be brought back:${RESET} only your ${BOLD}bookmarks and passwords${RESET}, by importing the files you exported.

${BOLD}Will be lost:${RESET}
  - open tabs, tab groups, pinned tabs and "restore last session"
  - history, cache and cookies
  - website sign-ins: ${BOLD}you'll need to sign back in to each site${RESET}
  - site permissions (camera, microphone, notifications, pop-ups): sites will ask again
  - autofill entries and saved payment methods
  - all $NAME settings and customizations
EOF
    if [[ "$BROWSER" == "edge" ]]; then
        printf '\n%sException:%s if you signed in to Edge with a Microsoft account and sync was on,\nthose synced items come back when Edge signs in again.\n' "$BOLD" "$RESET"
    fi
    cat <<EOF

Nothing is deleted. These will be renamed:
EOF
    local p
    while IFS= read -r p; do
        [[ -e "$p" ]] && printf '  %s  %s(%s)%s\n    -> %s\n' "$p" "$DIM" "$(human "$(size_kb "$p")")" "$RESET" "$(backup_name "$p")"
    done <<< "$(data_paths "$BROWSER")"
    printf '  %sTotal: %s%s\n\n' "$BOLD" "$(human "$SIZE_BEFORE")" "$RESET"
    confirm "OK to close $NAME now and back up its data?" || abort "cancelled before closing $NAME."
}

do_reset() {
    header "Step 3 of 4: Close and reset $NAME"
    if is_running "$BROWSER"; then
        quit_browser "$BROWSER" || abort "$NAME is still running."
    else
        echo "$NAME is not running."
    fi
    sleep 1

    local p dest moved=0
    BACKUPS=(); ORIGINALS=()
    while IFS= read -r p; do
        [[ -e "$p" ]] || continue
        dest=$(backup_name "$p")
        if mv "$p" "$dest" 2>/dev/null; then
            printf '  %sok%s  %s\n      -> %s\n' "$GREEN" "$RESET" "$p" "$dest"
            BACKUPS+=("$dest"); ORIGINALS+=("$p"); moved=$((moved + 1))
        else
            printf '  %sFAILED%s  %s\n' "$RED" "$RESET" "$p"
            [[ "$BROWSER" == "safari" ]] && printf '  %sGive Terminal Full Disk Access (System Settings > Privacy & Security) and try again.%s\n' "$YELLOW" "$RESET"
            if (( moved > 0 )); then
                printf '\n%sPartially reset. Already renamed:%s\n' "$RED" "$RESET"; printf '  %s\n' "${BACKUPS[@]}"
                echo "Rename them back (remove the '$SUFFIX' ending) to undo."
            fi
            exit 1
        fi
    done <<< "$(data_paths "$BROWSER")"

    # Safari prefs are cached by cfprefsd, which would write the old values back
    [[ "$BROWSER" == "safari" ]] && killall -u "$(id -un)" cfprefsd >/dev/null 2>&1
    printf '\n%s%s has been reset.%s\n' "$GREEN" "$NAME" "$RESET"
}

relaunch_and_restore() {
    header "Step 4 of 4: Restore your bookmarks and passwords"
    echo "Relaunching $NAME with a fresh profile..."
    open -a "$(app_name "$BROWSER")" 2>/dev/null || printf '%sCould not open %s - open it yourself.%s\n' "$YELLOW" "$NAME" "$RESET"
    echo
    restore_steps "$BROWSER"
    cat <<EOF

When you're done:
  - delete the exported password .csv
  - sign back in to websites and re-allow permissions when asked
EOF
    open_links restore_links
}

revert_prompt() {
    header "Keep the new profile or restore?"
    echo "  k) Keep the new $NAME profile (recommended if the problem is fixed)"
    echo "  r) Restore my previous $NAME browser data"
    local choice
    while true; do
        read -r -p "Choose k or r: " choice || exit 1
        case "$choice" in
            [kK]) REVERTED=no; return ;;
            [rR]) break ;;
        esac
    done
    echo
    echo "The new profile will be renamed to '$TMP_SUFFIX' and the '$SUFFIX' backup restored."
    echo "Anything you imported since the reset stays in the '$TMP_SUFFIX' folder."
    confirm "Close $NAME and restore now?" || { REVERTED=no; return; }
    if is_running "$BROWSER"; then
        quit_browser "$BROWSER" || { printf '%sRestore cancelled: %s is still running. Nothing was changed.%s\n' "$YELLOW" "$NAME" "$RESET"; REVERTED=no; return; }
    fi
    sleep 1
    local i orig bak tmp
    TMPS=()
    for i in "${!BACKUPS[@]}"; do
        orig="${ORIGINALS[$i]}"; bak="${BACKUPS[$i]}"; tmp=""
        if [[ -e "$orig" ]]; then
            tmp=$(free_name "$orig" "$TMP_SUFFIX")
            mv "$orig" "$tmp" 2>/dev/null || { revert_failed "$orig could not be renamed to $tmp"; return; }
            printf '  %sok%s  %s\n      -> %s\n' "$GREEN" "$RESET" "$orig" "$tmp"
        fi
        TMPS+=("$tmp")
        mv "$bak" "$orig" 2>/dev/null || { revert_failed "$bak could not be renamed back to $orig"; return; }
        printf '  %sok%s  %s\n      -> %s\n' "$GREEN" "$RESET" "$bak" "$orig"
    done
    [[ "$BROWSER" == "safari" ]] && killall -u "$(id -un)" cfprefsd >/dev/null 2>&1
    REVERTED=yes
    printf '\n%s%s has been restored.%s Relaunching...\n' "$GREEN" "$NAME" "$RESET"
    open -a "$(app_name "$BROWSER")" 2>/dev/null
}

revert_failed() {
    REVERTED=failed
    printf '\n%sRestore stopped: %s.%s\n' "$RED" "$1" "$RESET"
    echo "Check the folders listed in the summary and finish the renames by hand."
}

summary() {
    local p after=0 i
    header "Summary"
    printf '  Browser:          %s\n' "$NAME"
    printf '  Before reset:     %s\n' "$(human "$SIZE_BEFORE")"
    if [[ "$REVERTED" == "yes" ]]; then
        printf '  Rebuilt profile:  %s  %s(%s)%s\n' "$(human "$(size_kb "${TMPS[@]}")")" "$DIM" "$TMP_SUFFIX" "$RESET"
        printf '  Current profile:  %s  %s(your old data, restored)%s\n' "$(human "$(size_kb "${ORIGINALS[@]}")")" "$DIM" "$RESET"
        printf '  Outcome:          %sRestored browser profile%s\n' "$YELLOW" "$RESET"
        printf '  Started:          %s\n  Finished:         %s\n\n' "$STARTED" "$(date '+%Y-%m-%d %H:%M:%S')"
        echo "  Folders renamed:"
        for i in "${!BACKUPS[@]}"; do
            [[ -n "${TMPS[$i]}" ]] && printf '    %s (new)\n      -> %s\n' "${ORIGINALS[$i]}" "${TMPS[$i]}"
            printf '    %s\n      -> %s (restored)\n' "${BACKUPS[$i]}" "${ORIGINALS[$i]}"
        done
        printf '\n%sAll done.%s\n' "$GREEN" "$RESET"
        return
    fi
    for p in "${ORIGINALS[@]}"; do after=$((after + $(size_kb "$p"))); done
    printf '  After rebuild:    %s  %s(new profile, measured now)%s\n' "$(human "$after")" "$DIM" "$RESET"
    printf '  Kept as backup:   %s\n' "$(human "$(size_kb "${BACKUPS[@]}")")"
    [[ "$REVERTED" == "failed" ]] && printf '  Outcome:          %sRestore did not finish - see above%s\n' "$RED" "$RESET"
    printf '  Started:          %s\n  Finished:         %s\n\n' "$STARTED" "$(date '+%Y-%m-%d %H:%M:%S')"
    echo "  Folders renamed:"
    for i in "${!BACKUPS[@]}"; do
        printf '    %s\n      -> %s\n' "${ORIGINALS[$i]}" "${BACKUPS[$i]}"
    done
    printf '\n  %sNeed your old profile back?%s Run this script again, choose %s, then choose (r) to restore the backup.\n' "$BOLD" "$RESET" "$NAME"
    printf '\n%sAll done.%s\n' "$GREEN" "$RESET"
}

# ───────────────────────────────────────────────────────────────────────────────────────────── main
[[ "$(uname)" == "Darwin" ]] || { echo "This script is for macOS only."; exit 1; }
[[ $EUID -eq 0 ]] && { echo "Run this as yourself, not with sudo."; exit 1; }

STARTED=$(date '+%Y-%m-%d %H:%M:%S')
choose_browser
PATHS=(); while IFS= read -r p; do PATHS+=("$p"); done <<< "$(data_paths "$BROWSER")"
SIZE_BEFORE=$(size_kb "${PATHS[@]}")
handle_earlier_backups
backup_prompt
impact_prompt
do_reset
relaunch_and_restore
REVERTED=no
revert_prompt
summary
