#!/usr/bin/env bash
# scripts/install_ppt_cleanup.sh
# 一鍵安裝：將 PPT cleanup 排程到 macOS launchd（每日 03:15 執行）。
#
# 用法:
#   bash scripts/install_ppt_cleanup.sh                    # 安裝
#   bash scripts/install_ppt_cleanup.sh --uninstall        # 解除安裝
#   bash scripts/install_ppt_cleanup.sh --test             # 安裝後立刻跑一次

set -euo pipefail

# ── 路徑解析 ────────────────────────────────────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
LOG_DIR="${PROJECT_DIR}/logs"
SCRIPT_PATH="${SCRIPT_DIR}/ppt_cleanup.sh"

PLIST_NAME="com.openclaw.ppt-cleanup"
PLIST_SRC="${SCRIPT_DIR}/${PLIST_NAME}.plist"
PLIST_DST="${HOME}/Library/LaunchAgents/${PLIST_NAME}.plist"

mkdir -p "$LOG_DIR"
mkdir -p "$(dirname "$PLIST_DST")"
chmod +x "$SCRIPT_PATH"

# ── 解除安裝 ────────────────────────────────────────────────────────────
if [[ "${1:-}" == "--uninstall" ]]; then
    if launchctl list | grep -q "$PLIST_NAME"; then
        launchctl unload "$PLIST_DST" 2>/dev/null || true
    fi
    rm -f "$PLIST_DST"
    echo "✅ 已解除安裝 ${PLIST_NAME}"
    exit 0
fi

# ── 安裝 ────────────────────────────────────────────────────────────────
echo "🔧 安裝 PPT cleanup launchd job..."
echo "   PROJECT_DIR : $PROJECT_DIR"
echo "   SCRIPT_PATH : $SCRIPT_PATH"
echo "   LOG_DIR     : $LOG_DIR"
echo "   PLIST_DST   : $PLIST_DST"

# 替換 plist 中的 placeholder
sed -e "s|__SCRIPT_PATH__|${SCRIPT_PATH}|g" \
    -e "s|__LOG_DIR__|${LOG_DIR}|g" \
    -e "s|__PROJECT_DIR__|${PROJECT_DIR}|g" \
    "$PLIST_SRC" > "$PLIST_DST"

# 重新載入 launchd job
launchctl unload "$PLIST_DST" 2>/dev/null || true
launchctl load "$PLIST_DST"

echo "✅ 已安裝 ${PLIST_NAME}（每日 03:15 執行）"
echo ""
echo "驗證："
launchctl list | grep "$PLIST_NAME" || echo "   （job 尚未列出，可重啟 Mac 或執行 launchctl load）"

# ── 即刻測試 ────────────────────────────────────────────────────────────
if [[ "${1:-}" == "--test" ]]; then
    echo ""
    echo "🚀 立即觸發一次測試..."
    launchctl start "$PLIST_NAME"
    sleep 2
    echo "📋 stdout 最後 20 行："
    tail -20 "${LOG_DIR}/ppt_cleanup.stdout.log" 2>/dev/null || echo "   （尚無輸出）"
    echo "📋 stderr 最後 20 行："
    tail -20 "${LOG_DIR}/ppt_cleanup.stderr.log" 2>/dev/null || echo "   （無 stderr，正常）"
fi

echo ""
echo "🛠 後續操作："
echo "   立即觸發:   launchctl start $PLIST_NAME"
echo "   解除安裝:   bash $0 --uninstall"
echo "   查看日誌:   tail -f ${LOG_DIR}/ppt_cleanup.log"
