#!/bin/bash

# Check if script is run with sudo
if [ "$EUID" -ne 0 ]; then
    echo "Please run this script with sudo"
    exit 1
fi

# Make sure rclone is executable
chmod +x "$RCLONE_PATH"

# Configuration
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
LAUNCH_AGENTS_DIR="$HOME/Library/LaunchAgents"
RCLONE_PATH="$SCRIPT_DIR/rclone"
CONF_PATH="$SCRIPT_DIR/rclone.conf"
REMOTE_NAME="3DFF"
DLNA_PLIST="com.3dflickfix.dlna.plist"
MOUNT_PLIST="com.3dflickfix.mount.plist"
DLNA_LOG="$SCRIPT_DIR/DLNAlog.txt"
MOUNT_LOG="$SCRIPT_DIR/Mountlog.txt"

echo "This will set up 3DFlickFix as a service"
echo
echo "A mounted drive makes it easy to view and download the collection right from Finder."
echo
echo "A DLNA server makes it easy to stream on a phone, TV, or VR headset."
echo
read -p "Press Enter to continue..."
clear

echo "Please choose an option:"
echo "1. Mount the collection as a drive"
echo "2. Set up a DLNA server on your local network"
echo "3. Both (Mount as drive and set up DLNA server)"
read -p "Enter your choice (1/2/3): " choice

# Check if macFUSE is installed for mounting
check_macfuse() {
    # Check for the FUSE kernel extension
    if [ -e "/Library/Filesystems/macfuse.fs" ] || [ -e "/Library/Filesystems/osxfuse.fs" ]; then
        return 0
    fi
    
    # Check for various possible package IDs
    for pkg in "com.github.osxfuse.pkg.Core" "io.macfuse.installer.pkg" "io.macfuse.installer" "com.github.macfuse"; do
        if pkgutil --pkg-info "$pkg" >/dev/null 2>&1; then
            return 0
        fi
    done
    
    echo "macFUSE is not installed. It's required for mounting remote filesystems."
    echo "Please install macFUSE from: https://osxfuse.github.io or https://github.com/osxfuse/osxfuse/releases"
    echo "Alternatively, you can find an older disk image in the same directory as this script."
    echo "After installing macFUSE, you'll need to restart your computer."
    read -p "Do you want to continue anyway? (y/N): " continue_anyway
    if [[ ! $continue_anyway =~ ^[Yy]$ ]]; then
        exit 1
    fi
}

# Function to create and load a launchd service
create_launchd_service() {
    local label=$1
    local command=$2
    local plist_path="$LAUNCH_AGENTS_DIR/$label"
    
    # Create LaunchAgents directory if it doesn't exist
    mkdir -p "$LAUNCH_AGENTS_DIR"
    
    # Create the plist file
    cat > "$plist_path" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>$label</string>
    <key>ProgramArguments</key>
    <array>
        $command
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>WorkingDirectory</key>
    <string>$SCRIPT_DIR</string>
    <key>EnvironmentVariables</key>
    <dict>
        <key>PATH</key>
        <string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
    </dict>
</dict>
</plist>
EOF

    # Set proper permissions
    chown $SUDO_USER "$plist_path"
    chmod 644 "$plist_path"
    
    # Unload existing service if it exists
    su - $SUDO_USER -c "launchctl unload -w $plist_path" 2>/dev/null
    
    # Load the service
    su - $SUDO_USER -c "launchctl load -w $plist_path"
}

# Function to remove a launchd service
remove_service() {
    local plist_path="$LAUNCH_AGENTS_DIR/$1"
    if [ -f "$plist_path" ]; then
        su - $SUDO_USER -c "launchctl unload -w $plist_path"
        rm "$plist_path"
    fi
}

mount_drive() {
    # Check for macFUSE before mounting
    check_macfuse

    # Create mount log file
    touch "$MOUNT_LOG"
    chown $SUDO_USER "$MOUNT_LOG"
    chmod 644 "$MOUNT_LOG"
    
    remove_service "$MOUNT_PLIST"
    read -p "What do you want to name the mountpoint? (folder name) " mountpoint
    
    # Create mount point with proper permissions
    mkdir -p "$SCRIPT_DIR/$mountpoint"
    chown $SUDO_USER "$SCRIPT_DIR/$mountpoint"
    
    # Create mount service command
    local mount_cmd="        <string>$RCLONE_PATH</string>
        <string>mount</string>
        <string>$REMOTE_NAME:</string>
        <string>$SCRIPT_DIR/$mountpoint</string>
        <string>--allow-other</string>
        <string>--dir-cache-time</string>
        <string>72h</string>
        <string>--drive-chunk-size</string>
        <string>64M</string>
        <string>--log-level</string>
        <string>INFO</string>
        <string>--vfs-read-chunk-size</string>
        <string>32M</string>
        <string>--vfs-read-chunk-size-limit</string>
        <string>off</string>
        <string>--config</string>
        <string>$CONF_PATH</string>
        <string>--log-file</string>
        <string>$MOUNT_LOG</string>
        <string>--vfs-cache-mode</string>
        <string>full</string>"
    
    create_launchd_service "$MOUNT_PLIST" "$mount_cmd"
    echo "Drive mounted to $SCRIPT_DIR/$mountpoint"
}

setup_dlna() {
    remove_service "$DLNA_PLIST"

    # Create DLNA log file
    touch "$DLNA_LOG"
    chown $SUDO_USER "$DLNA_LOG"
    chmod 644 "$DLNA_LOG"
        
    # Create DLNA service command
    local dlna_cmd="        <string>$RCLONE_PATH</string>
        <string>serve</string>
        <string>dlna</string>
        <string>$REMOTE_NAME:</string>
        <string>--name</string>
        <string>3DFlickFix</string>
        <string>--dir-cache-time</string>
        <string>72h</string>
        <string>--drive-chunk-size</string>
        <string>64M</string>
        <string>--log-level</string>
        <string>INFO</string>
        <string>--vfs-read-chunk-size</string>
        <string>32M</string>
        <string>--vfs-read-chunk-size-limit</string>
        <string>off</string>
        <string>--config</string>
        <string>$CONF_PATH</string>
        <string>--log-file</string>
        <string>$DLNA_LOG</string>
        <string>--vfs-cache-mode</string>
        <string>full</string>"
    
    create_launchd_service "$DLNA_PLIST" "$dlna_cmd"
    echo "DLNA server set up for $REMOTE_NAME"
}

case $choice in
    1)
        mount_drive
        ;;
    2)
        setup_dlna
        ;;
    3)
        mount_drive
        setup_dlna
        ;;
    *)
        echo "Invalid choice. Exiting."
        exit 1
        ;;
esac

echo "Waiting for services to start..."
sleep 5

# Verify services are running
echo "Checking service status..."
if pgrep -f "rclone.*mount" > /dev/null; then
    echo "Mount service is running"
else
    echo "Warning: Mount service failed to start. Check Mountlog.txt for details"
fi

if pgrep -f "rclone.*dlna" > /dev/null; then
    echo "DLNA service is running"
else
    echo "Warning: DLNA service failed to start. Check DLNAlog.txt for details"
fi

echo "Script completed successfully"