#!/bin/bash

# Script to package each shapefile layer into its own zip file
# Usage: ./package_shapefiles.sh [-r] [directory]
#   -r: Process directories recursively
#   directory: Path to shapefile directory (default: current directory)

# Default values
RECURSIVE=false
SHAPEFILE_DIR="."

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case "$1" in
        -r|--recursive)
            RECURSIVE=true
            shift
            ;;
        -h|--help)
            echo "Usage: $0 [-r] [directory]"
            echo "  -r, --recursive: Process directories recursively"
            echo "  directory: Path to shapefile directory (default: current directory)"
            exit 0
            ;;
        *)
            SHAPEFILE_DIR="$1"
            shift
            ;;
    esac
done

# Check if directory exists
if [ ! -d "$SHAPEFILE_DIR" ]; then
    echo "Error: Directory $SHAPEFILE_DIR does not exist"
    exit 1
fi

# Function to process shapefiles in a directory
process_directory() {
    local dir="$1"
    echo "Processing directory: $dir"
    
    # Change to the directory
    cd "$dir" || return
    
    # Find all .shp files (the main shapefile component)
    local found_shp=false
    for shp_file in *.shp; do
        # Skip if no .shp files found
        if [ ! -e "$shp_file" ]; then
            break
        fi
        
        found_shp=true
        # Get the base name without extension
        base_name="${shp_file%.shp}"
        echo "Processing shapefile layer: $base_name"
        
        # Create a temporary directory for this layer
        mkdir -p "$base_name"_temp
        
        # Find all files with the same base name but different extensions
        # Common shapefile extensions: .shp, .shx, .dbf, .prj, .sbn, .sbx, .fbn, .fbx, .ain, .aih, .atx, .ixs, .mxs, .xml, .cpg
        for file in "$base_name".*; do
            if [ -f "$file" ]; then
                echo "  Adding file: $file"
                cp "$file" "$base_name"_temp/
            fi
        done
        
        # Create zip file
        zip -j "$base_name.zip" "$base_name"_temp/*
        
        # Clean up temporary directory
        rm -rf "$base_name"_temp
        
        echo "  Created: $base_name.zip"
        echo ""
    done
    
    if [ "$found_shp" = false ]; then
        echo "No .shp files found in $dir"
    fi
    
    # Process subdirectories if recursive option is enabled
    if [ "$RECURSIVE" = true ]; then
        for subdir in */; do
            if [ -d "$subdir" ]; then
                # Save current directory
                local current_dir=$(pwd)
                # Process subdirectory
                process_directory "$(realpath "$subdir")"
                # Return to current directory
                cd "$current_dir" || exit 1
            fi
        done
    fi
}

# Start processing
process_directory "$(realpath "$SHAPEFILE_DIR")"

echo "All shapefile layers have been packaged into individual zip files." 