#!/bin/bash

# Handle Ctrl+C gracefully
trap ctrl_c INT

function ctrl_c() {
    echo ""
    echo "Cancelled by user."
    exit 0
}

# Function to read input with tab completion for paths
read_path() {
    local prompt="$1"
    local input
    
    # Use read with -e flag for readline editing (enables tab completion)
    read -e -p "$prompt" input
    echo "$input"
}

# Get source folder
SOURCE=$(read_path "Enter source folder path: ")

# Validate source exists
if [ ! -d "$SOURCE" ]; then
    echo "Error: Source folder '$SOURCE' does not exist!"
    exit 1
fi

# Get destination folders
echo "Enter destination folders (one per line, empty line to finish):"
echo "(Tip: Use TAB for folder completion, Ctrl+C to cancel)"
DESTINATIONS=()
while true; do
    dest=$(read_path "Destination $((${#DESTINATIONS[@]} + 1)): ")
    if [ -z "$dest" ]; then
        break
    fi
    # Create destination if it doesn't exist
    if [ ! -d "$dest" ]; then
        read -p "Destination '$dest' doesn't exist. Create it? (y/n): " create
        if [ "$create" = "y" ]; then
            mkdir -p "$dest"
        else
            continue
        fi
    fi
    DESTINATIONS+=("$dest")
done

# Validate we have destinations
if [ ${#DESTINATIONS[@]} -eq 0 ]; then
    echo "Error: No destination folders provided!"
    exit 1
fi

# Display summary
echo ""
echo "=== Summary ==="
echo "Source: $SOURCE"
echo "Destinations:"
for i in "${!DESTINATIONS[@]}"; do
    echo "  $((i + 1)). ${DESTINATIONS[$i]}"
done

# Get list of items in source
items=("$SOURCE"/*)
total=${#items[@]}
items_per_dest=$((total / ${#DESTINATIONS[@]}))

echo ""
echo "Total items to split: $total"
echo "Items per destination: ~$items_per_dest"
echo ""

read -p "Proceed with copy? (y/n): " confirm
if [ "$confirm" != "y" ]; then
    echo "Cancelled."
    exit 0
fi

# Distribute items
echo ""
echo "Starting distribution..."
for i in "${!DESTINATIONS[@]}"; do
    start=$((i * items_per_dest))
    if [ $i -eq $((${#DESTINATIONS[@]} - 1)) ]; then
        # Last destination gets remainder
        end=$total
    else
        end=$(((i + 1) * items_per_dest))
    fi
    
    echo ""
    echo "Copying to ${DESTINATIONS[$i]} (items $((start + 1)) to $end)..."
    for ((j=start; j<end; j++)); do
        item_name=$(basename "${items[$j]}")
        echo "  -> $item_name"
        rsync -a "${items[$j]}" "${DESTINATIONS[$i]}/"
    done
done

echo ""
echo "Distribution complete!"
