#!/bin/bash
# VoiceIME 安装脚本
# 从同目录 VoiceIME.dmg 提取 VoiceIME.app 并安装到目标目录

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_NAME="VoiceIME"
DMG_PATH="$SCRIPT_DIR/${APP_NAME}.dmg"
DEFAULT_INSTALL_DIR="$HOME/Applications"
APP_DEST_DIR="$DEFAULT_INSTALL_DIR"
APP_DEST="$APP_DEST_DIR/${APP_NAME}.app"

show_help() {
    cat <<EOF
VoiceIME 安装脚本

用法：
  bash build/install.sh           从同目录 ${APP_NAME}.dmg 安装到 ~/Applications
  bash build/install.sh clean     清除 Keychain 与系统权限记录
  bash build/install.sh help      显示帮助
  bash build/install.sh --target /path/to/install

说明：
  - 默认读取与 install.sh 同目录下的 ${APP_NAME}.dmg
  - 安装时会从 DMG 中提取 ${APP_NAME}.app 并复制到目标目录
  - 保留 Keychain 清理函数，但普通安装流程不会自动调用
EOF
}

clear_keychain() {
    echo "🧹 清理 VoiceIME Keychain 与本地认证记录..."
    security delete-generic-password -s com.voiceime -a credentials >/dev/null 2>&1 || true
    defaults delete com.voiceime.app chatgptExpiresAt >/dev/null 2>&1 || true
}

reset_permissions() {
    echo "🔑 重置系统权限记录..."
    tccutil reset ListenEvent com.voiceime.app 2>/dev/null || true
    tccutil reset Accessibility com.voiceime.app 2>/dev/null || true
    tccutil reset ScreenCapture com.voiceime.app 2>/dev/null || true
    tccutil reset Microphone com.voiceime.app 2>/dev/null || true
}

run_clean() {
    clear_keychain
    reset_permissions
    echo "✅ 清理完成"
}

while [ $# -gt 0 ]; do
    case "$1" in
        clean)
            run_clean
            exit 0
            ;;
        help|-h|--help)
            show_help
            exit 0
            ;;
        --target)
            if [ $# -lt 2 ]; then
                echo "❌ --target 需要指定目录"
                exit 1
            fi
            APP_DEST_DIR="$2"
            APP_DEST="$APP_DEST_DIR/${APP_NAME}.app"
            shift 2
            ;;
        *)
            echo "❌ 未知参数：$1"
            echo ""
            show_help
            exit 1
            ;;
    esac
done

echo "==============================="
echo "  VoiceIME 安装程序"
echo "==============================="
echo ""

if [ ! -f "$DMG_PATH" ]; then
    echo "❌ 找不到安装包：$DMG_PATH"
    exit 1
fi

MOUNT_POINT="$(mktemp -d "${TMPDIR:-/tmp}/voiceime-mount.XXXXXX")"
cleanup() {
    hdiutil detach "$MOUNT_POINT" -quiet >/dev/null 2>&1 || true
    rm -rf "$MOUNT_POINT"
}
trap cleanup EXIT

echo "💿 挂载 DMG..."
hdiutil attach "$DMG_PATH" -mountpoint "$MOUNT_POINT" -nobrowse -quiet

APP_SRC="$MOUNT_POINT/${APP_NAME}.app"
if [ ! -d "$APP_SRC" ]; then
    echo "❌ DMG 中未找到 ${APP_NAME}.app"
    exit 1
fi

mkdir -p "$APP_DEST_DIR"

if pgrep -x "$APP_NAME" >/dev/null 2>&1; then
    echo "🔄 正在关闭旧版 ${APP_NAME}..."
    pkill -x "$APP_NAME" 2>/dev/null || true
    sleep 1
fi

if [ -d "$APP_DEST" ]; then
    echo "🗑  移除旧版本..."
    rm -rf "$APP_DEST"
fi

echo "📦 安装到 $APP_DEST ..."
cp -R "$APP_SRC" "$APP_DEST"

echo "✍️  对安装目录应用执行最终签名..."
codesign --force --sign - --deep "$APP_DEST" >/dev/null 2>&1 || true

echo "🧼 清理安装包隔离属性..."
xattr -dr com.apple.quarantine "$APP_DEST" >/dev/null 2>&1 || true

reset_permissions

echo ""
echo "✅ 安装完成！"
echo ""

echo "🚀 启动 VoiceIME..."
open "$APP_DEST"

echo ""
echo "==============================="
echo "  启动后请完成权限授权："
echo ""
echo "  1. 输入监控：系统设置 → 隐私与安全 → 输入监控"
echo "     找到 VoiceIME，打开开关，然后点击"
echo "     应用内的「重启 VoiceIME」按钮"
echo ""
echo "  2. 辅助功能：系统弹窗点「打开系统设置」勾选"
echo ""
echo "  3. 屏幕录制：截图 OCR 首次使用时按提示授权"
echo "     授权后建议点击应用内的「热重启 VoiceIME」"
echo ""
echo "  4. 麦克风：首次按录音快捷键时系统弹窗确认"
echo ""
echo "  默认快捷键："
echo "  • 开始录音：⌘⇧O（按住说话，松开转录）"
echo "  • 智能回复：⌃⇧U（选中文字后触发）"
echo "  • 截图 OCR：⌘⇧P（框选区域后识别文字）"
echo "==============================="
