#!/bin/bash

# PPT Add-in Installation Script for Mac
# This script downloads manifest.xml and installs it to the correct WEF directory

set -e  # Exit on any error

echo "========================================"
echo "PPT Add-in Installation for Mac"
echo "========================================"

# Get current user
USER=$(whoami)
echo "Current user: $USER"

# Define WEF directory for PowerPoint
WEF_DIR="/Users/$USER/Library/Containers/com.microsoft.Powerpoint/Data/Documents/wef"
echo "WEF directory: $WEF_DIR"

# Create WEF directory if it doesn't exist
echo "Creating WEF directory..."
mkdir -p "$WEF_DIR"

# Download manifest.xml from network
echo "Downloading manifest.xml from network..."
if curl -s -o "$WEF_DIR/manifest.xml" "https://xiaomishuppt.com/manifest.xml"; then
    echo "manifest.xml downloaded successfully"
else
    echo "Network download failed, trying local file..."
    if [ -f "$(dirname "$0")/manifest_template.xml" ]; then
        cp "$(dirname "$0")/manifest_template.xml" "$WEF_DIR/manifest.xml"
        echo "Using local manifest_template.xml"
    else
        echo "Error: Cannot get manifest.xml file!"
        exit 1
    fi
fi

# Verify manifest.xml was created
if [ -f "$WEF_DIR/manifest.xml" ]; then
    echo "manifest.xml successfully installed to: $WEF_DIR/manifest.xml"
    
    # Extract Add-in ID from manifest for verification
    ADDIN_ID=$(grep -o '<Id>[^<]*</Id>' "$WEF_DIR/manifest.xml" | sed 's/<Id>//;s/<\/Id>//')
    if [ -n "$ADDIN_ID" ]; then
        echo "Add-in ID: $ADDIN_ID"
    fi
else
    echo "Error: manifest.xml was not created!"
    exit 1
fi

echo ""
echo "========================================"
echo "PPT Add-in Installation Complete!"
echo "========================================"
echo "manifest.xml has been installed to the WEF directory"
echo "Please restart PowerPoint and load the add-in"
echo ""
echo "If add-in does not appear, please check:"
echo "1. PowerPoint has been restarted"
echo "2. Developer mode is enabled"
echo "3. Network connection is normal"
echo "4. WEF directory exists: $WEF_DIR"
echo "========================================"

# Make the script executable
chmod +x "$0"

echo "Press any key to continue..."
read -n 1 -s
