#!/bin/bash

set -e  # 任何命令失败时终止脚本

# 切换到脚本所在目录
cd "$(dirname "$0")"
echo "当前目录是: $(pwd)"

# 定义目标目录
TARGET_DIR="$HOME/planet-helper"

echo "星球助手的默认工作目录是 \"$TARGET_DIR\""

# 检查目标目录是否存在
if [ ! -d "$TARGET_DIR" ]; then
    echo "目标目录不存在，正在创建并复制文件..."
    mkdir -p "$TARGET_DIR"

    cp -R "Google Chrome for Testing.app" "$TARGET_DIR/Google Chrome for Testing.app"
    cp -R "data" "$TARGET_DIR/data"
    cp -R "星球助手.app" "$TARGET_DIR/星球助手.app"

    echo "安装完成！"
    open "$TARGET_DIR"
    exit 0
fi

# 目标目录已存在，询问用户操作
echo "目标目录已存在。"
echo "请选择操作："
echo "1. 强制覆盖安装（会删除所有数据和应用到回收站）"
echo "2. 只更新程序（会保留数据，但会更新app）"
read -p "请输入选项（1 或 2）：" choice

if [ "$choice" == "1" ]; then
    echo "正在强制覆盖安装..."
    
    # 将目标目录移动到回收站
    osascript -e "tell application \"Finder\" to delete POSIX file \"$TARGET_DIR\""
    mkdir -p "$TARGET_DIR"
    
    cp -R "Google Chrome for Testing.app" "$TARGET_DIR/Google Chrome for Testing.app"
    cp -R "data" "$TARGET_DIR/data"
    cp -R "星球助手.app" "$TARGET_DIR/星球助手.app"
    
    echo "强制覆盖安装完成！"
elif [ "$choice" == "2" ]; then
    echo "正在更新程序..."
    
    # 将旧的 星球助手.app 移动到回收站
    [ -e "$TARGET_DIR/星球助手.app" ] && osascript -e "tell application \"Finder\" to delete POSIX file \"$TARGET_DIR/星球助手.app\""
    
    cp -R "星球助手.app" "$TARGET_DIR/星球助手.app"
    
    echo "程序更新完成！"
else
    echo "无效的选项，退出脚本。"
    exit 1
fi

# 完成提示
echo "操作成功完成！"
open "$TARGET_DIR"

# 等待用户按任意键退出
read -n 1 -s -r -p "按任意键退出..."
echo