#!/bin/zsh
set -u

# Mavom tutorial maintenance template, 2026-11-29.
# Disabled until the reader verifies the app/image/account mapping and backups.
CONFIGURED=0
USER_HOME="$HOME"
VOLUME="/Volumes/WeChatData"
PRIMARY_IMAGE_SUBDIR="WeChat-main"
SECONDARY_IMAGE_SUBDIR="WeChat-second"
PRIMARY_ACCOUNT_DIR=""
SECONDARY_ACCOUNT_DIR=""

if [[ "$CONFIGURED" != 1 || -z "$PRIMARY_ACCOUNT_DIR" || -z "$SECONDARY_ACCOUNT_DIR" ]]; then
  print -r -- "Template disabled: fill the volume, image folders and account directories, then set CONFIGURED=1."
  exit 2
fi
for account_dir in "$PRIMARY_ACCOUNT_DIR" "$SECONDARY_ACCOUNT_DIR"; do
  if [[ "$account_dir" == */* || "$account_dir" == . || "$account_dir" == .. ]]; then
    print -r -- "Account settings must be single directory names, not paths."
    exit 2
  fi
done
for image_dir in "$PRIMARY_IMAGE_SUBDIR" "$SECONDARY_IMAGE_SUBDIR"; do
  if [[ -z "$image_dir" || "$image_dir" == */* || "$image_dir" == . || "$image_dir" == .. ]]; then
    print -r -- "Image folder settings must be nonempty single directory names."
    exit 2
  fi
done
if [[ "$PRIMARY_IMAGE_SUBDIR" == "$SECONDARY_IMAGE_SUBDIR" || "$VOLUME" != /Volumes/* ]]; then
  print -r -- "Use distinct image folders and an external volume mounted under /Volumes."
  exit 2
fi

LOG="$USER_HOME/Desktop/微信外置聊天记录恢复.log"
TS="$(date '+%Y%m%d-%H%M%S')"
RECOVERY_TTY="$(/usr/bin/tty 2>/dev/null || true)"
MIGRATION_PENDING=0
SCREEN_CAPTURE_PENDING=0
SCREEN_CAPTURE_REOPENED=0
RECOVERY_LOCK_FD=""

exec > >(tee -a "$LOG") 2>&1

echo "=============================="
echo "微信外置聊天记录一键恢复"
echo "时间：$(date '+%Y-%m-%d %H:%M:%S')"
echo "=============================="

wait_before_close() {
  echo ""
  echo "按回车关闭窗口。"
  read -r _
}

fail() {
  if [[ -n "$RECOVERY_LOCK_FD" ]]; then
    zsystem flock -u "$RECOVERY_LOCK_FD"
  fi
  echo ""
  echo "失败：$*"
  echo "日志：$LOG"
  wait_before_close
  exit 1
}

close_terminal_on_success() {
  [[ "${TERM_PROGRAM:-}" == "Apple_Terminal" && "$RECOVERY_TTY" == /dev/ttys* ]] || return 0

  # Finished windows retain their old TTY, which macOS may reuse. Resolve the
  # unique busy window now, while this foreground recovery shell is still alive.
  local terminal_window_id
  terminal_window_id="$(/usr/bin/osascript - "$RECOVERY_TTY" 2>> "$LOG" <<'APPLESCRIPT'
on run argv
  set recoveryTty to item 1 of argv
  set matchingWindowIds to {}
  if not (application id "com.apple.Terminal" is running) then return
  tell application id "com.apple.Terminal"
    repeat with terminalWindow in windows
      repeat with terminalTab in tabs of terminalWindow
        if tty of terminalTab is recoveryTty and busy of terminalTab then
          if (count of tabs of terminalWindow) is not 1 then return "本次窗口含其他标签页，已保留窗口。"
          set end of matchingWindowIds to id of terminalWindow
        end if
      end repeat
    end repeat
  end tell
  if (count of matchingWindowIds) is 1 then return item 1 of matchingWindowIds
  return "无法唯一识别本次终端窗口，已保留窗口。"
end run
APPLESCRIPT
)" || { echo "终端自动关闭未能启动，详情见日志。"; return 0; }
  [[ "$terminal_window_id" == <-> ]] || { echo "$terminal_window_id"; return 0; }

  echo "执行完成，正在自动关闭本次终端窗口（ID：$terminal_window_id）..."
  # Let the foreground shell and logger exit before closing the captured window.
  /usr/bin/nohup /usr/bin/osascript - "$RECOVERY_TTY" "$terminal_window_id" >> "$LOG" 2>&1 <<'APPLESCRIPT' &!
on run argv
  set recoveryTty to item 1 of argv
  set recoveryWindowId to (item 2 of argv) as integer

  repeat 20 times
    delay 0.5
    if not (application id "com.apple.Terminal" is running) then return
    tell application id "com.apple.Terminal"
      if not (exists window id recoveryWindowId) then
        if (count of windows) is 0 then quit
        return
      end if
      set recoveryWindow to window id recoveryWindowId
      if (count of tabs of recoveryWindow) is not 1 then return "本次窗口含其他标签页，已保留窗口。"
      set recoveryTab to tab 1 of recoveryWindow
      if tty of recoveryTab is not recoveryTty then return
      if not busy of recoveryTab then
        close recoveryWindow saving no
        if (count of windows) is 0 then
          quit
          return "已关闭本次终端窗口，并退出 Terminal。"
        end if
        return "已关闭本次终端窗口，其他终端窗口继续保留。"
      end if
    end tell
  end repeat
  return "终端仍有运行中的进程，已保留窗口；恢复结果见上方日志。"
end run
APPLESCRIPT
}

is_mounted_at() {
  local mountpoint="$1"
  mount | /usr/bin/grep -F " on $mountpoint " >/dev/null 2>&1
}

plist_value() {
  /usr/bin/plutil -extract "$2" raw - 2>/dev/null <<< "$1"
}

# Return the single APFS volume of this exact image, including an unmounted
# volume. Empty output means detached; a failed or ambiguous lookup is an error.
attached_apfs_volume() {
  local image="$1" inventory count entries image_path entity device_info
  local i j matched=0 result=""
  inventory="$(/usr/bin/hdiutil info -plist)" || return 1
  count="$(plist_value "$inventory" images)" || return 1
  for ((i=0; i<count; i++)); do
    image_path="$(plist_value "$inventory" "images.$i.image-path")" || continue
    [[ "$image_path" == "$image" ]] || continue
    (( matched == 0 )) || return 1
    matched=1
    entries="$(plist_value "$inventory" "images.$i.system-entities")" || return 1
    for ((j=0; j<entries; j++)); do
      entity="$(plist_value "$inventory" "images.$i.system-entities.$j.dev-entry")" || return 1
      [[ "$entity" == /dev/disk<->s<-> ]] || continue
      device_info="$(/usr/sbin/diskutil info -plist "$entity")" || return 1
      [[ "$(plist_value "$device_info" FilesystemType)" == apfs ]] || continue
      [[ -z "$result" ]] || return 1
      result="$entity"
    done
  done
  (( matched == 0 )) || [[ -n "$result" ]] || return 1
  print -r -- "$result"
}

app_is_running() {
  local app="$1"
  pgrep -f "/Applications/$app/Contents/MacOS/WeChat" >/dev/null 2>&1
}

quit_app_if_needed() {
  local bundle="$1"
  local app="$2"

  if ! app_is_running "$app"; then
    return 0
  fi

  echo "检测到 $app 正在运行，正在请求退出..."
  osascript -e "tell application id \"$bundle\" to quit" >/dev/null 2>&1 || true

  for _i in {1..15}; do
    if ! app_is_running "$app"; then
      echo "$app 已退出。"
      return 0
    fi
    sleep 1
  done

  fail "$app 仍在运行。请手动退出后再双击此脚本。"
}

repair_wechat2_if_needed() {
  /usr/bin/python3 - "/Applications/WeChat.app" "/Applications/WeChat2.app" \
    "$USER_HOME/Library/Caches/wechat2-app-repair.lock" <<'PY_WECHAT2_REPAIR'
import ctypes
import fcntl
import hashlib
import json
import os
from pathlib import Path
import plistlib
import re
import subprocess
import sys
import tempfile
import time

MAIN_ID = "com.tencent.xinWeChat"
SECOND_ID = "com.tencent.xinWeChat2"
TEAM_ID = "5A4RE8SF68"
LSREGISTER = "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister"
VENDOR_REQUIREMENT = 'anchor apple generic and certificate leaf[subject.OU] = "5A4RE8SF68"'
QUIT_BY_PID = r"""
ObjC.import("AppKit");
function run(argv) {
    var app = $.NSRunningApplication.runningApplicationWithProcessIdentifier(Number(argv[0]));
    if (!app || app.isNil()) return;
    if (ObjC.unwrap(app.bundleURL.path) !== argv[1]) {
        throw new Error("目标进程的应用路径已变化");
    }
    if (!app.terminate) throw new Error("微信2暂未接受退出请求");
}
"""

def run(args):
    result = subprocess.run(args, capture_output=True, timeout=180)
    if result.returncode:
        detail = result.stderr.decode(errors="replace").strip()[-1600:]
        raise RuntimeError("{} 执行失败：{}".format(Path(args[0]).name, detail))
    return result.stdout

def info(app):
    return plistlib.loads((app / "Contents/Info.plist").read_bytes())

def entitlements(app):
    raw = run(["/usr/bin/codesign", "-d", "--entitlements", ":-", str(app)])
    return plistlib.loads(raw) if raw.strip() else {}

def verify(app, vendor=False):
    args = ["/usr/bin/codesign", "--verify", "--deep", "--strict"]
    if vendor:
        args += ["-R=" + VENDOR_REQUIREMENT]
    run(args + [str(app)])

def verify_independent(app):
    verify(app)
    ent = entitlements(app)
    groups = ent.get("com.apple.security.application-groups", [])
    expected = TEAM_ID + "." + SECOND_ID
    main_group = TEAM_ID + "." + MAIN_ID
    if (info(app).get("CFBundleIdentifier") != SECOND_ID
            or ent.get("com.apple.security.app-sandbox") is not True
            or ent.get("com.apple.application-identifier") != expected
            or expected not in groups
            or any(g == main_group or g.startswith(main_group + ".") for g in groups)):
        raise RuntimeError("微信2的独立应用标识或沙盒应用组校验失败")

def fingerprint(app):
    if not app.exists():
        return None
    executable = info(app)["CFBundleExecutable"]
    result = {}
    for relative in ["Contents/Info.plist", "Contents/_CodeSignature/CodeResources",
                     "Contents/MacOS/" + executable]:
        if not (app / relative).is_file():
            result[relative] = None
            continue
        digest = hashlib.sha256()
        with (app / relative).open("rb") as stream:
            for chunk in iter(lambda: stream.read(1024 * 1024), b""):
                digest.update(chunk)
        result[relative] = digest.hexdigest()
    return result

def process_rows():
    rows = []
    for line in run(["/bin/ps", "-axo", "pid=,comm="]).decode().splitlines():
        fields = line.strip().split(None, 1)
        if len(fields) == 2:
            rows.append((fields[0], fields[1]))
    return rows

def quit_target(app):
    executable = str(app / "Contents/MacOS" / info(app)["CFBundleExecutable"])
    for pid, command in process_rows():
        if command == executable:
            run(["/usr/bin/osascript", "-l", "JavaScript", "-e",
                 QUIT_BY_PID, pid, str(app)])
    for _ in range(30):
        if not any(command.startswith(str(app) + "/") for _, command in process_rows()):
            return
        time.sleep(1)
    raise RuntimeError("微信2或其更新进程仍在运行，请等待退出后重试")

def convert(value):
    if isinstance(value, str):
        value = re.sub(r"com\.tencent\.xinWeChat(?=$|[.\-])", SECOND_ID, value)
        return value.replace("com.tencent.xWechat.DebugHelper", "com.tencent.xWechat2.DebugHelper")
    if isinstance(value, list):
        return [convert(item) for item in value]
    if isinstance(value, dict):
        return {key: convert(item) for key, item in value.items()}
    return value

def rebuild(source, candidate, work):
    run(["/usr/bin/ditto", str(source), str(candidate)])
    verify(candidate, vendor=True)
    plists = [p for p in candidate.rglob("Info.plist")
              if p.parent.name == "Contents"
              and not any(part.endswith(".framework") for part in p.relative_to(candidate).parts)]
    changed = []
    # Frameworks retain their vendor identifiers; sign application helpers inside-out.
    for index, plist in enumerate(sorted(plists, key=lambda p: len(p.parts), reverse=True)):
        before = plistlib.loads(plist.read_bytes())
        bundle_id = before.get("CFBundleIdentifier", "")
        if not (bundle_id == MAIN_ID or bundle_id.startswith(MAIN_ID + ".")
                or bundle_id == "com.tencent.xWechat.DebugHelper"):
            continue
        bundle = plist.parent.parent
        ent = convert(entitlements(bundle))
        plist.write_bytes(plistlib.dumps(convert(before), fmt=plistlib.FMT_BINARY, sort_keys=False))
        args = ["/usr/bin/codesign", "--force", "--sign", "-", "--options=0", "--timestamp=none"]
        if ent:
            ent_file = work / ("entitlements-{}.plist".format(index))
            ent_file.write_bytes(plistlib.dumps(ent))
            args += ["--entitlements", str(ent_file)]
        run(args + [str(bundle)])
        changed.append(str(bundle.relative_to(candidate)))
    verify_independent(candidate)
    return changed

def atomic_rename(source, destination, flags):
    # macOS renamex_np: RENAME_SWAP=2 and RENAME_EXCL=4.
    library = ctypes.CDLL(None, use_errno=True)
    rename = library.renamex_np
    rename.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint]
    rename.restype = ctypes.c_int
    if rename(os.fsencode(source), os.fsencode(destination), flags):
        error = ctypes.get_errno()
        raise OSError(error, os.strerror(error), str(destination))

def repair(main, target):
    if target.is_symlink():
        raise RuntimeError("微信2应用路径是符号链接，请先核实应用位置")
    previous_info = info(target) if target.exists() else None
    previous_id = previous_info.get("CFBundleIdentifier") if previous_info else None
    if previous_id == SECOND_ID:
        try:
            verify_independent(target)
            print("微信2独立身份与签名正常。", flush=True)
            return {"status": "healthy"}
        except RuntimeError:
            main_version = info(main)
            if any(previous_info.get(k) != main_version.get(k)
                   for k in ("CFBundleShortVersionString", "CFBundleVersion")):
                raise RuntimeError("微信2校验异常，且主微信版本不同；请完成微信2更新后重试")
            source = main
    elif previous_id == MAIN_ID:
        source = target
    elif previous_id is None and not target.exists():
        source = main
    else:
        raise RuntimeError("微信2应用标识无法识别：{}".format(previous_id))

    source_info = info(source)
    if source_info.get("CFBundleIdentifier") != MAIN_ID:
        raise RuntimeError("修复来源不是官方微信应用标识")
    verify(source, vendor=True)
    source_fingerprint = fingerprint(source)
    previous_fingerprint = fingerprint(target)
    print("检测到微信2需要修复，保留版本 {}（{}）并重建独立身份。".format(
        source_info.get("CFBundleShortVersionString"), source_info.get("CFBundleVersion")), flush=True)
    if target.exists():
        quit_target(target)

    work = Path(tempfile.mkdtemp(prefix=".WeChat2-auto-repair-", dir=str(target.parent)))
    candidate = work / "WeChat2.app"
    backup = work / "WeChat2-before-repair.app.backup"
    print("修复工作目录：{}".format(work), flush=True)
    changed = rebuild(source, candidate, work)
    if fingerprint(source) != source_fingerprint or fingerprint(target) != previous_fingerprint:
        raise RuntimeError("应用在修复期间发生更新，请重新运行 command")
    verify(source, vendor=True)
    if any(command.startswith(str(target) + "/") for _, command in process_rows()):
        raise RuntimeError("微信2在替换前重新启动，请退出后重试")
    record = {"source": str(source), "target": str(target), "version": source_info["CFBundleShortVersionString"],
              "build": source_info["CFBundleVersion"], "modifiedBundles": changed, "backup": str(backup)}
    (work / "repair.json").write_text(json.dumps(record, ensure_ascii=False, indent=2) + "\n")

    had_target = target.exists()
    atomic_rename(candidate, target, 2 if had_target else 4)
    try:
        verify_independent(target)
        run([LSREGISTER, "-f", str(target)])
    except BaseException:
        if had_target:
            atomic_rename(candidate, target, 2)
            subprocess.run([LSREGISTER, "-f", str(target)], capture_output=True)
        else:
            atomic_rename(target, candidate, 4)
        print("安装校验失败，已回退本次替换。", flush=True)
        raise
    if had_target:
        # A failed backup rename leaves the original intact in the work directory.
        try:
            candidate.rename(backup)
        except OSError:
            backup = candidate
        print("原微信2程序备份：{}".format(backup), flush=True)
    print("微信2自动修复完成，独立身份与签名校验通过。", flush=True)
    return {"status": "repaired", "backup": str(backup), "work": str(work)}

if __name__ == "__main__":
    try:
        main_app, second_app, lock_path = map(Path, sys.argv[1:])
        descriptor = os.open(str(lock_path), os.O_CREAT | os.O_RDWR, 0o600)
        with os.fdopen(descriptor, "r+") as lock:
            fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            repair(main_app, second_app)
    except Exception as error:
        print("微信2自动修复失败：{}".format(error), flush=True)
        sys.exit(1)
PY_WECHAT2_REPAIR
  local repair_status=$?
  (( repair_status == 0 )) || fail "微信2自动修复未完成，详情见上方日志。"
}

maintain_screen_capture_after_update() {
  /usr/bin/python3 - "$USER_HOME/Library/Application Support/WeChatExternalLauncher/screen-capture-state.json" <<'PY_WECHAT_SCREEN_CAPTURE'
import hashlib
import json
import os
from pathlib import Path
import plistlib
import sqlite3
import subprocess
import sys
import tempfile
import time

APPS = (
    ("微信", "com.tencent.xinWeChat", Path("/Applications/WeChat.app")),
    ("微信2", "com.tencent.xinWeChat2", Path("/Applications/WeChat2.app")),
)
TCC_DATABASE = Path("/Library/Application Support/com.apple.TCC/TCC.db")
SETTINGS_URL = "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"


def command(args, data=None):
    return subprocess.run(args, input=data, capture_output=True, timeout=20)


def installation_snapshot(app, bundle):
    info = plistlib.loads((app / "Contents/Info.plist").read_bytes())
    if app.is_symlink() or info.get("CFBundleIdentifier") != bundle:
        raise RuntimeError("应用路径或标识不符")
    result = command(["/usr/bin/codesign", "-d", "-r-", "--verbose=4", str(app)])
    lines = (result.stdout + result.stderr).decode(errors="replace").splitlines()
    requirements = [line.lstrip("# ") for line in lines if "designated =>" in line]
    code_hashes = [line.split("=", 1)[1] for line in lines if line.startswith("CDHash=")]
    if result.returncode or len(requirements) != 1 or len(code_hashes) != 1:
        raise RuntimeError("无法读取应用签名标识")
    return {
        "version": str(info.get("CFBundleShortVersionString", "")),
        "build": str(info.get("CFBundleVersion", "")),
        "internalVersion": str(info.get("WeChatBundleVersion", "")),
        "requirementKey": hashlib.sha256(requirements[0].encode()).hexdigest(),
        "codeHash": code_hashes[0],
    }


def access_row(bundle):
    # Read only this app's screen-capture row. Never write the TCC database.
    db = sqlite3.connect(TCC_DATABASE.as_uri() + "?mode=ro", uri=True, timeout=2)
    try:
        rows = db.execute(
            "SELECT auth_value, csreq, last_modified FROM access "
            "WHERE service=? AND client=? AND client_type=0",
            ("kTCCServiceScreenCapture", bundle),
        ).fetchall()
    finally:
        db.close()
    if len(rows) > 1:
        raise RuntimeError("授权记录不唯一")
    return rows[0] if rows else None


def inspect(app, bundle):
    row = access_row(bundle)
    if row is None:
        return "missing", row
    if row[0] != 2:
        return "disabled", row
    if not isinstance(row[1], bytes) or not row[1]:
        return "unknown", row
    # -R - consumes the compiled requirement from stdin. -R= would instead
    # interpret its argument as literal requirement source text.
    result = command(["/usr/bin/codesign", "--verify", "--strict", "-R", "-", str(app)], row[1])
    if result.returncode == 0:
        return "granted", row
    if result.returncode == 3:
        return "stale", row
    return "unknown", row


def read_state(path):
    try:
        value = json.loads(path.read_text())
        return value if isinstance(value, dict) else {}
    except (OSError, ValueError):
        return {}


def write_state(path, value):
    path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    descriptor, temporary = tempfile.mkstemp(prefix=".screen-capture-", dir=str(path.parent))
    try:
        with os.fdopen(descriptor, "w") as stream:
            json.dump(value, stream, ensure_ascii=False, indent=2)
            stream.write("\n")
        os.replace(temporary, path)
    finally:
        if os.path.exists(temporary):
            os.unlink(temporary)


UI_DRIVER = r"""
function run(argv) {
    var appPath = argv[0];
    var phase = argv[1] || 'start';
    if (['/Applications/WeChat.app', '/Applications/WeChat2.app'].indexOf(appPath) < 0) {
        throw new Error('不允许的应用路径');
    }
    var events = Application('System Events');
    if (!events.uiElementsEnabled()) return JSON.stringify({status: 'accessibility_required'});
    var matches = events.applicationProcesses.whose({bundleIdentifier: 'com.apple.systempreferences'})();
    if (matches.length !== 1 || !matches[0].windows().length) {
        return JSON.stringify({status: 'waiting_for_settings'});
    }
    var proc = matches[0];
    var win = proc.windows[0];
    var all = [win].concat(win.entireContents());
    function attr(el, key) {
        try { return el.attributes.byName(key).value(); } catch (error) { return null; }
    }
    function role(el) {
        try { return el.role(); } catch (error) { return ''; }
    }
    function text(el) {
        var values = [attr(el, 'AXTitle'), attr(el, 'AXDescription'), attr(el, 'AXHelp')];
        try { values.push(el.name()); } catch (error) {}
        return values.filter(function(value) { return typeof value === 'string'; }).join(' ');
    }
    var nodes = all.map(function(el) { return {el: el, role: role(el)}; });
    // Detect secure fields by role only. Never request their value or properties.
    var secure = nodes.some(function(node) {
        return node.role === 'AXSecureTextField' ||
            (node.role === 'AXTextField' && attr(node.el, 'AXSubrole') === 'AXSecureTextField');
    });
    if (secure) return JSON.stringify({status: phase === 'preflight' ? 'settings_busy' : 'needs_auth', phase: phase});
    if (phase === 'preflight') {
        return JSON.stringify({status: 'preflight_ok', window: win.name()});
    }
    if (!proc.frontmost()) return JSON.stringify({status: 'user_interrupted', phase: phase});

    var buttons = nodes.filter(function(node) { return node.role === 'AXButton'; });
    function buttonById(id) {
        return buttons.filter(function(node) { return attr(node.el, 'AXIdentifier') === id; })[0];
    }
    function press(button) {
        if (!button || !button.el.enabled()) throw new Error('目标按钮不可用');
        button.el.click();
    }
    var openPanel = nodes.filter(function(node) {
        return ['AXSheet', 'AXDialog', 'AXWindow'].indexOf(node.role) >= 0 &&
            attr(node.el, 'AXIdentifier') === 'open-panel';
    })[0];

    if (openPanel) {
        if (phase === 'start' || phase === 'waiting_panel') {
            events.keystroke('g', {using: ['command down', 'shift down']});
            return JSON.stringify({status: 'progress', phase: 'go_to'});
        }
        if (phase === 'go_to') {
            var fields = nodes.filter(function(node) {
                if (node.role === 'AXComboBox') return true;
                if (node.role !== 'AXTextField' || attr(node.el, 'AXSubrole') === 'AXSearchField') return false;
                var label = text(node.el) + ' ' + String(attr(node.el, 'AXPlaceholderValue') || '');
                return !/搜索|Search/i.test(label) && !attr(node.el, 'AXURL');
            });
            var combos = fields.filter(function(node) { return node.role === 'AXComboBox'; });
            var pathField = combos[0] || (fields.length === 1 ? fields[0] : null);
            if (!pathField) return JSON.stringify({status: 'waiting_for_path_field', phase: phase});
            pathField.el.value = appPath;
            if (pathField.el.value() !== appPath) throw new Error('未能写入目标应用路径');
            events.keyCode(36);
            return JSON.stringify({status: 'progress', phase: 'path_entered'});
        }
        if (phase === 'path_entered') {
            function samePath(value) {
                if (value !== null && typeof value !== 'string') value = String(value);
                if (typeof value !== 'string') return false;
                try { value = decodeURIComponent(value.replace(/^file:\/\//, '')); } catch (error) {}
                return value.replace(/\/$/, '') === appPath;
            }
            function selected(el) {
                for (var depth = 0; depth < 5 && el; depth++) {
                    if (attr(el, 'AXSelected') === true) return true;
                    try { if (el.selected()) return true; } catch (error) {}
                    try { el = el.parent(); } catch (error) { el = null; }
                }
                return false;
            }
            var exactSelection = nodes.some(function(node) {
                return node.role === 'AXTextField' && samePath(attr(node.el, 'AXURL')) && selected(node.el);
            });
            if (!exactSelection) return JSON.stringify({status: 'waiting_for_exact_selection', phase: phase});
            press(buttonById('OKButton'));
            return JSON.stringify({status: 'progress', phase: 'submitted'});
        }
        return JSON.stringify({status: 'unexpected_picker_state', phase: phase});
    }

    if (phase === 'submitted') {
        var reopen = buttonById('action-button-1');
        if (reopen && /退出并重新打开|Quit.*Reopen/i.test(text(reopen.el))) {
            var message = nodes.filter(function(node) { return node.role === 'AXStaticText'; }).map(function(node) {
                var value = attr(node.el, 'AXValue');
                return typeof value === 'string' ? value : text(node.el);
            }).join(' ');
            var expected = appPath.indexOf('WeChat2.app') >= 0 ? /WeChat2|微信2/ : /WeChat|微信/;
            if (!expected.test(message)) return JSON.stringify({status: 'unrelated_dialog', phase: phase});
            press(reopen);
            return JSON.stringify({status: 'progress', phase: 'submitted'});
        }
    }

    var paneTitle = String(win.name() || '');
    var screenPane = /录屏与系统录音|屏幕录制|Screen.*(?:Recording|Audio)/i.test(paneTitle);
    if (!screenPane) return JSON.stringify({status: 'wrong_settings_page', phase: phase});
    if (phase === 'submitted') return JSON.stringify({status: 'ready_for_verification', phase: phase});
    if (phase === 'waiting_panel') return JSON.stringify({status: 'waiting_for_panel', phase: phase});
    if (phase !== 'start') {
        return JSON.stringify({status: 'cancelled', phase: phase});
    }
    if (nodes.some(function(node) { return ['AXSheet', 'AXDialog'].indexOf(node.role) >= 0; })) {
        return JSON.stringify({status: 'unrelated_dialog', phase: phase});
    }
    var addButtons = buttons.filter(function(node) { return /^(添加|Add)(\s|$)/.test(text(node.el).trim()); });
    var add = addButtons[0];
    if (!add) {
        // The upper recording list has one scroll area followed by Add/Remove.
        // This fallback is limited to the verified recording pane structure.
        var groups = nodes.filter(function(node) { return node.role === 'AXGroup'; });
        for (var index = 0; index < groups.length && !add; index++) {
            var children = groups[index].el.uiElements();
            var childButtons = children.filter(function(el) { return role(el) === 'AXButton'; });
            if (childButtons.length === 2 && children.some(function(el) { return role(el) === 'AXScrollArea'; })) {
                add = {el: childButtons[0]};
            }
        }
    }
    if (!add) return JSON.stringify({status: 'unsupported_settings_layout', phase: phase});
    press(add);
    return JSON.stringify({status: 'progress', phase: 'waiting_panel'});
}
"""


QUIT_APP_BY_PID = r'''
ObjC.import('AppKit');
function run(argv) {
    var app = $.NSRunningApplication.runningApplicationWithProcessIdentifier(Number(argv[0]));
    if (!app || app.isNil()) return;
    if (ObjC.unwrap(app.bundleURL.path) !== argv[1]) throw new Error('应用进程路径已变化');
    if (!app.terminate) throw new Error('应用未接受正常退出请求');
}
'''


def ui_step(app, phase):
    result = subprocess.run(
        ['/usr/bin/osascript', '-l', 'JavaScript', '-e', UI_DRIVER, str(app), phase],
        capture_output=True, timeout=45,
    )
    if result.returncode:
        raise RuntimeError(result.stderr.decode(errors='replace').strip()[-600:])
    value = json.loads(result.stdout)
    if not isinstance(value, dict) or not isinstance(value.get('status'), str):
        raise RuntimeError('系统设置返回了无法识别的状态')
    return value


def notify_auth(name):
    print('\a需要系统验证：请在“隐私与安全”的验证窗口输入本机密码或使用触控 ID。验证后将自动继续添加' + name + '截图权限。', flush=True)
    command([
        '/usr/bin/osascript', '-e',
        'display notification "请在系统设置中完成密码或触控 ID 验证；验证后自动继续。" with title "微信截图权限需要系统验证" sound name "Glass"',
    ])


def process_rows():
    result = command(['/bin/ps', '-axo', 'pid=,comm='])
    if result.returncode:
        raise RuntimeError('无法核对微信进程')
    return [line.strip().split(None, 1) for line in result.stdout.decode().splitlines()
            if len(line.strip().split(None, 1)) == 2]


def quit_for_permission(app):
    executable = str(app / 'Contents/MacOS/WeChat')
    for pid, path in process_rows():
        if path == executable:
            result = command(['/usr/bin/osascript', '-l', 'JavaScript', '-e', QUIT_APP_BY_PID, pid, str(app)])
            if result.returncode:
                raise RuntimeError('微信暂未接受退出请求，已保留现有进程')
    for _ in range(30):
        if not any(path.startswith(str(app) + '/') for _, path in process_rows()):
            return
        time.sleep(1)
    raise RuntimeError('微信仍在运行，未强制退出')


def automatic_readd(name, bundle, app, snapshot):
    if (name, bundle, app) not in APPS or installation_snapshot(app, bundle) != snapshot:
        raise RuntimeError('授权目标应用在操作前已变化')
    verify = command(['/usr/bin/codesign', '--verify', '--deep', '--strict', str(app)])
    if verify.returncode:
        raise RuntimeError('待授权应用签名校验失败')

    preflight = ui_step(app, 'preflight')
    if preflight['status'] not in ('preflight_ok', 'waiting_for_settings'):
        raise RuntimeError('系统设置自动操作暂不可用：' + preflight['status'])
    print('正在通过系统设置自动重新添加' + name + '截图权限...', flush=True)
    try:
        quit_for_permission(app)
        if command(['/usr/bin/open', SETTINGS_URL]).returncode:
            raise RuntimeError('无法打开录屏权限页面')
        command(['/usr/bin/osascript', '-e', 'tell application id "com.apple.systempreferences" to activate'])
        phase = 'start'
        notified = False
        deadline = time.monotonic() + 120
        permission = 'unknown'
        while time.monotonic() < deadline:
            if installation_snapshot(app, bundle) != snapshot:
                raise RuntimeError('微信在授权期间再次更新，已停止本次自动添加')
            result = ui_step(app, phase)
            status = result['status']
            if status == 'needs_auth':
                if not notified:
                    notify_auth(name)
                    notified = True
                    deadline = time.monotonic() + 300
                time.sleep(1)
                continue
            if status == 'progress':
                phase = result['phase']
            elif status == 'ready_for_verification':
                permission, _ = inspect(app, bundle)
                if permission == 'granted':
                    print(name + '截图权限已自动添加，并通过当前签名核验。', flush=True)
                    return 'granted'
            elif status in ('waiting_for_settings', 'waiting_for_panel', 'waiting_for_path_field', 'waiting_for_exact_selection'):
                pass
            else:
                raise RuntimeError('系统设置自动添加已停止：' + status)
            time.sleep(0.4)
        if notified:
            print(name + '系统验证尚未完成，下次运行 command 会继续此次更新后的授权。', flush=True)
            return 'awaiting_auth'
        raise RuntimeError('系统设置未在时限内完成添加；最后授权状态：' + permission)
    finally:
        reopened = command(['/usr/bin/open', '-g', str(app)])
        if reopened.returncode:
            raise RuntimeError(name + '未能重新打开，请查看日志')


def main(state_path):
    previous = read_state(state_path)
    previous_apps = previous.get("apps", {})
    if not isinstance(previous_apps, dict):
        previous_apps = {}
    next_state = {"schemaVersion": 3, "checkedAt": int(time.time()), "apps": {}}
    pending = []
    automatic = []
    uncertain = False
    updates = 0
    initialized = 0
    for name, bundle, app in APPS:
        old = previous_apps.get(bundle, {})
        if not isinstance(old, dict):
            old = {}
        entry = dict(old)
        try:
            current = installation_snapshot(app, bundle)
        except (OSError, ValueError, RuntimeError, subprocess.TimeoutExpired) as error:
            uncertain = True
            print(name + "版本记录暂无法核对，已跳过截图权限维护：" + str(error), flush=True)
            next_state["apps"][bundle] = entry
            continue

        key = current["requirementKey"]
        entry.update(requirementKey=key, installation=current)
        old_installation = old.get("installation")
        if not isinstance(old_installation, dict) or not old_installation:
            # First run and migration from the earlier state format only create
            # a baseline. Missing history is not evidence of an app update.
            if old.get("requirementKey") != key:
                entry["status"] = "baseline_recorded"
            initialized += 1
            print(name + "当前版本已记录，后续仅更新后检查截图权限。", flush=True)
            next_state["apps"][bundle] = entry
            continue
        resuming_auth = old.get("awaitingAuthFor") == current
        if old_installation == current and not resuming_auth:
            # No TCC database reads, resets, or settings windows on normal runs.
            next_state["apps"][bundle] = entry
            continue

        updates += 1
        print(name + ("继续完成此次更新后的系统验证。" if resuming_auth else
                      "检测到版本或签名更新，检查本次更新后的截图权限。"), flush=True)
        status = "unknown"
        try:
            status, row = inspect(app, bundle)
            if status == "stale":
                # Re-read immediately before the scoped reset, in case the user
                # has already re-authorized this app in System Settings.
                fresh_status, fresh_row = inspect(app, bundle)
                if fresh_status == "granted":
                    status = "granted"
                elif (fresh_status == "stale" and fresh_row == row
                      and installation_snapshot(app, bundle) == current):
                    print(name + "截图授权仍绑定旧版，正在清理这一项失效授权。", flush=True)
                    reset = command(["/usr/bin/tccutil", "reset", "ScreenCapture", bundle])
                    if reset.returncode:
                        status = "reset_failed"
                        print(name + "授权清理未完成，请在系统设置中移除后重新添加。", flush=True)
                    else:
                        status, _ = inspect(app, bundle)
                        if status != "granted":
                            status = "needs_grant"
                else:
                    status = "changed_during_check"
        except (OSError, ValueError, RuntimeError, sqlite3.Error, subprocess.TimeoutExpired) as error:
            print(name + "截图权限暂无法核验：" + str(error), flush=True)
            status = "unknown"

        entry.update(status=status, lastMaintenanceAt=int(time.time()))
        if status == "granted":
            entry["lastVerifiedRequirement"] = key
            entry.pop("awaitingAuthFor", None)
            print(name + "截图权限有效，已核对当前程序签名。", flush=True)
        else:
            automatic.append((name, bundle, app, current))
        next_state["apps"][bundle] = entry

    # Record the update before UI work. Normal launches never invoke the UI
    # driver; an unfinished password verification belongs to this update only.
    write_state(state_path, next_state)
    for name, bundle, app, current in automatic:
        entry = next_state["apps"][bundle]
        try:
            outcome = automatic_readd(name, bundle, app, current)
        except Exception as error:
            outcome = "automatic_add_failed"
            print(name + "截图权限自动添加未完成：" + str(error), flush=True)
        entry["status"] = outcome
        if outcome == "granted":
            entry["lastVerifiedRequirement"] = current["requirementKey"]
            entry.pop("awaitingAuthFor", None)
        else:
            pending.append((name, app))
            if outcome == "awaiting_auth":
                entry["awaitingAuthFor"] = current
            else:
                entry.pop("awaitingAuthFor", None)
        write_state(state_path, next_state)
    if not updates and not initialized and not uncertain:
        print("微信版本未变化，跳过截图权限维护。", flush=True)
    if pending:
        print("此次更新后的截图授权仍未完成，详情见上方日志。", flush=True)
        return 20
    return 21 if uncertain else (22 if automatic else 0)


if __name__ == "__main__":
    try:
        sys.exit(main(Path(sys.argv[1])))
    except Exception as error:
        print("截图权限检查未完成：{}；微信启动结果不受此检查影响。".format(error), flush=True)
        sys.exit(21)
PY_WECHAT_SCREEN_CAPTURE
  local permission_status=$?
  case "$permission_status" in
    0) SCREEN_CAPTURE_PENDING=0 ;;
    22) SCREEN_CAPTURE_PENDING=0; SCREEN_CAPTURE_REOPENED=1 ;;
    20) SCREEN_CAPTURE_PENDING=1; SCREEN_CAPTURE_REOPENED=1 ;;
    *) SCREEN_CAPTURE_PENDING=2; SCREEN_CAPTURE_REOPENED=1 ;;
  esac
}

check_app() {
  local app="$1"
  local expected_bundle="$2"
  local app_path="/Applications/$app"
  local plist="$app_path/Contents/Info.plist"
  local actual_bundle

  [[ -d "$app_path" ]] || fail "找不到应用：$app_path"
  actual_bundle="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$plist" 2>/dev/null || true)"

  if [[ "$actual_bundle" != "$expected_bundle" ]]; then
    fail "$app 包标识异常（当前：${actual_bundle:-未知}，应为：$expected_bundle）。请先修复应用，脚本未启动微信以免读错账号数据。"
  fi

  codesign --verify --deep --strict "$app_path" >/dev/null 2>&1 || \
    fail "$app 签名校验失败，请先修复应用。"

  echo "$app 校验通过：$expected_bundle"
}

restore_bundle() {
  local bundle="$1"
  local app="$2"
  local expected_account="$3"
  local data_bundle="$4"
  local base="$USER_HOME/Library/Containers/$bundle/Data/Documents"
  local mountpoint="$base/xwechat_files"
  local image="$VOLUME/$data_bundle/xwechat_files.sparsebundle"
  local device info old_mount="" default_mount uuid="" mounted_device
  local -a local_entries

  echo ""
  echo "处理：$app"

  [[ -d "$VOLUME" ]] || fail "外置盘未挂载：$VOLUME"
  [[ -e "$image" ]] || fail "找不到外置数据：$image"

  if ! is_mounted_at "$mountpoint"; then
    device="$(attached_apfs_volume "$image")" || fail "无法唯一识别外置映像的 APFS 卷：$image"
    if [[ -n "$device" ]]; then
      info="$(/usr/sbin/diskutil info -plist "$device")" || fail "无法读取卷信息：$device"
      uuid="$(plist_value "$info" VolumeUUID)" || fail "无法读取外置卷 UUID：$device"
      [[ -n "$uuid" ]] || fail "此外置卷没有可核验的 UUID：$device"
      old_mount="$(plist_value "$info" MountPoint)" || fail "无法读取原挂载位置：$device"
      if [[ -n "$old_mount" ]]; then
        default_mount="/Volumes/$(plist_value "$info" VolumeName)"
        [[ "$old_mount" == "$default_mount" || "$old_mount" == "$default_mount "<-> ]] || \
          fail "此外置映像正在其他自定义目录使用：$old_mount"
        [[ -d "$old_mount/$expected_account" ]] || fail "现挂载卷中未找到账号目录：$expected_account"
      fi
    fi

    quit_app_if_needed "$bundle" "$app"
    mkdir -p "$base" || fail "无法创建目录：$base"

    local_entries=("$mountpoint"/*(DN[1]))
    if [[ -L "$mountpoint" || ( -e "$mountpoint" && ! -d "$mountpoint" ) || ${#local_entries} -gt 0 ]]; then
      local backup="$mountpoint.local_not_mounted_$TS"
      [[ ! -e "$backup" && ! -L "$backup" ]] || backup="${backup}_$$"
      mv "$mountpoint" "$backup" || fail "无法保护当前本机目录：$mountpoint"
      echo "已保护当前本机目录：$backup"
    fi

    mkdir -p "$mountpoint" || fail "无法创建挂载点：$mountpoint"
    if [[ -n "$old_mount" ]]; then
      echo "发现映像已挂载在 $old_mount，正在挂回微信目录..."
      info="$(/usr/sbin/diskutil info -plist "$old_mount")" || fail "原挂载位置已变化。"
      [[ "$(plist_value "$info" VolumeUUID)" == "$uuid" && "$(plist_value "$info" MountPoint)" == "$old_mount" && "$(attached_apfs_volume "$image")" == "$device" ]] || \
        fail "原挂载卷已变化，请重新运行脚本。"
      /usr/sbin/diskutil unmount "$old_mount" || fail "无法正常卸载 $old_mount，请关闭占用该卷的文件后重试。"
      device="$(attached_apfs_volume "$image")" || fail "卸载后无法识别映像设备：$image"
    fi
    if [[ -n "$device" ]]; then
      info="$(/usr/sbin/diskutil info -plist "$device")" || fail "无法读取待挂载设备：$device"
      [[ "$(plist_value "$info" VolumeUUID)" == "$uuid" ]] || fail "待挂载设备的 UUID 已变化。"
      if ! /usr/sbin/diskutil mount nobrowse -mountPoint "$mountpoint" "$device"; then
        if [[ -n "$old_mount" && "$(attached_apfs_volume "$image")" == "$device" ]]; then
          /usr/sbin/diskutil mount "$device" || echo "原卷仍已连接，可以再次运行脚本。"
        fi
        fail "无法将外置卷挂到微信目录：$mountpoint"
      fi
    else
      echo "正在连接并挂载外置映像..."
      /usr/sbin/diskutil image attach --mountPoint "$mountpoint" --mountOptions nobrowse "$image" >/dev/null || \
        fail "挂载失败：$image"
    fi
  else
    echo "已经挂载，无需重复操作。"
  fi

  is_mounted_at "$mountpoint" || fail "挂载后校验失败：$mountpoint"
  device="$(attached_apfs_volume "$image")" || fail "无法核实外置映像设备：$image"
  info="$(/usr/sbin/diskutil info -plist "$mountpoint")" || fail "无法核实挂载点：$mountpoint"
  mounted_device="$(plist_value "$info" DeviceNode)" || fail "无法读取挂载卷设备。"
  [[ -n "$device" && "$mounted_device" == "$device" && "$(plist_value "$info" MountPoint)" == "$mountpoint" ]] || \
    fail "$app 的挂载点与预期外置映像不匹配：$image"
  # Verify existing account directories against the reader-configured mapping.
  # A pending migration marker never skips the account-directory check.
  [[ -d "$mountpoint/$expected_account" ]] || \
    fail "$app 外置数据中未找到账号目录：$expected_account"
  if [[ -f "$mountpoint/.wechat-migration-pending" ]]; then
    MIGRATION_PENDING=1
    echo "提示：$app 的历史聊天导入尚未核验完成；账号目录：$expected_account"
  fi

  echo "挂载完成：$mountpoint"
  echo "映像校验通过：$image"
  echo "预期账号目录：$expected_account"
  df -h "$mountpoint" | tail -n 1
}

verify_running_path() {
  local app="$1"
  local expected_path="$2"
  local expected_process_bundle="$3"
  local process_line=""

  for _i in {1..30}; do
    process_line="$(ps -axo command | /usr/bin/grep -F "/Applications/$app/Contents/MacOS/WeChatAppEx.app/Contents/MacOS/WeChatAppEx" | /usr/bin/grep -v grep | head -n 1 || true)"
    if [[ -n "$process_line" ]] && ps -axo comm | /usr/bin/grep -Fx "/Applications/$app/Contents/MacOS/WeChat" >/dev/null; then
      break
    fi
    sleep 1
  done

  [[ -n "$process_line" ]] || fail "$app 启动后未检测到微信数据进程。"
  ps -axo comm | /usr/bin/grep -Fx "/Applications/$app/Contents/MacOS/WeChat" >/dev/null || \
    fail "$app 的主进程尚未就绪。"
  [[ " $process_line " == *" --wechat-files-path=$expected_path "* ]] || \
    fail "$app 实际读取路径不正确，已停止完成提示。"
  [[ " $process_line " == *" --bundle-id=$expected_process_bundle "* ]] || \
    fail "$app 实际账号容器标识不正确，已停止完成提示。"

  echo "$app 正在使用外置数据目录：$expected_path"
}

is_mounted_at "$VOLUME" || fail "请先连接外置盘：$VOLUME"
lock_file="${TMPDIR:-/tmp}/wechat-external-recovery-${EUID}.lock"
(umask 077; : >> "$lock_file") || fail "无法创建运行锁。"
zmodload zsh/system || fail "无法加载系统文件锁。"
zsystem flock -t 0 -f RECOVERY_LOCK_FD "$lock_file" || fail "已有恢复脚本正在运行，请等待其完成。"

check_app "WeChat.app" "com.tencent.xinWeChat"
repair_wechat2_if_needed
check_app "WeChat2.app" "com.tencent.xinWeChat2"

# Reader-configured image and account mapping; no automatic account guessing.
restore_bundle "com.tencent.xinWeChat" "WeChat.app" "$PRIMARY_ACCOUNT_DIR" "$PRIMARY_IMAGE_SUBDIR"
restore_bundle "com.tencent.xinWeChat2" "WeChat2.app" "$SECONDARY_ACCOUNT_DIR" "$SECONDARY_IMAGE_SUBDIR"

echo ""
echo "正在打开两个微信..."
open /Applications/WeChat.app >/dev/null 2>&1 || fail "无法打开 /Applications/WeChat.app"
open /Applications/WeChat2.app >/dev/null 2>&1 || fail "无法打开 /Applications/WeChat2.app"

verify_running_path \
  "WeChat.app" \
  "$USER_HOME/Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files" \
  "5A4RE8SF68.com.tencent.xinWeChat"
verify_running_path \
  "WeChat2.app" \
  "$USER_HOME/Library/Containers/com.tencent.xinWeChat2/Data/Documents/xwechat_files" \
  "5A4RE8SF68.com.tencent.xinWeChat2"

echo ""
maintain_screen_capture_after_update

if (( SCREEN_CAPTURE_REOPENED )); then
  echo "正在核验重新打开的微信..."
verify_running_path \
  "WeChat.app" \
  "$USER_HOME/Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files" \
  "5A4RE8SF68.com.tencent.xinWeChat"
verify_running_path \
  "WeChat2.app" \
  "$USER_HOME/Library/Containers/com.tencent.xinWeChat2/Data/Documents/xwechat_files" \
  "5A4RE8SF68.com.tencent.xinWeChat2"
fi

echo ""
if (( MIGRATION_PENDING )); then
  echo "完成：两个微信均已连接外置目录；历史聊天导入仍待核验。"
else
  echo "完成：两个微信均已挂载并读取外置聊天记录。"
fi
if (( SCREEN_CAPTURE_PENDING == 1 )); then
  echo "此次更新后的截图授权尚未完成，请查看上方系统验证或自动添加结果。"
elif (( SCREEN_CAPTURE_PENDING == 2 )); then
  echo "截图权限状态未完整核验，详情见上方日志。"
fi
echo "日志：$LOG"
close_terminal_on_success
exit 0
