#!/bin/bash

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

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

# Function to remove a service
remove_service() {
    local plist_name="$1"
    local plist_path="$LAUNCH_AGENTS_DIR/$plist_name"
    
    if [ -f "$plist_path" ]; then
        # Unload the service as the regular user
        su - $SUDO_USER -c "launchctl unload -w $plist_path"
        
        # Remove the plist file
        rm "$plist_path"
        echo "Service $plist_name stopped and removed successfully."
    else
        echo "Service $plist_name not found or already removed."
    fi
}

# Remove both services
remove_service "$MOUNT_PLIST"
remove_service "$DLNA_PLIST"

# Clean up mount point
if [ -d "$SCRIPT_DIR" ]; then
    mount_points=()
    for dir in "$SCRIPT_DIR"/*; do
        if [ -d "$dir" ] && [[ ! "$dir" == */.* ]]; then
            mount_points+=("$dir")
        fi
    done
    
    if [ ${#mount_points[@]} -gt 0 ]; then
        echo "Found potential mount points:"
        printf '%s\n' "${mount_points[@]}"
        read -p "Do you want to remove these directories? (y/N): " remove_dirs
        case $remove_dirs in
            [Yy]*)
                for dir in "${mount_points[@]}"; do
                    rm -rf "$dir"
                    echo "Removed: $dir"
                done
                echo "Mount points cleaned up."
                ;;
            *)
                echo "Mount points not removed."
                ;;
        esac
    else
        echo "No mount points found in $SCRIPT_DIR"
    fi
else
    echo "Script directory not found. Unable to clean up mount points."
fi

# Clean up logs
read -p "Do you want to clean up the logs? (Y/n): " clean_logs
case $clean_logs in
    [Nn]*)
        echo "Logs not cleaned up."
        ;;
    *)
        rm -f "$DLNA_LOG" "$MOUNT_LOG"
        echo "Logs cleaned up."
        ;;
esac

# Kill any remaining rclone processes (just in case)
pkill -f "rclone"

echo "Service removal completed."
