#!/bin/bash

usage() {
    echo "Usage: $0 -ext [extensions] -f [folder]"
    echo "  -ext  List of file extensions to include in the zip without the dot (e.g., xyz inp out)"
    echo "  -f    Target directory to zip"
    exit 1
}

exit_with_message() {
    echo "$1"
    exit 1
}

# Initial check for no arguments
if [ "$#" -eq 0 ]; then
    echo "No arguments provided. You will be prompted to enter the necessary information."
    # Prompt for extensions
    echo "Enter file extensions to include (space-separated, no dots, e.g., xyz inp out):"
    read -ra extensions
    if [ ${#extensions[@]} -eq 0 ]; then
        exit_with_message "No extensions provided. Exiting."
    fi
    # Prompt for folder
    echo "Enter the target folder to zip:"
    read folder
    if [ -z "$folder" ]; then
        exit_with_message "No folder provided. Exiting."
    fi
else
    # Initialize variables
    declare -a extensions
    folder=""

    # Parse command line arguments
    while [[ "$#" -gt 0 ]]; do
        case $1 in
            -ext) shift
                  while [[ "$#" -gt 0 && "${1:0:1}" != "-" ]]; do
                      extensions+=("${1#.}")
                      shift
                  done ;;
            -f)   shift
                  folder="${1%/}"
                  shift ;;
            *)    echo "Unknown parameter passed: $1"
                  usage ;;
        esac
    done

    # Verify if extensions and folder are properly specified
    if [ ${#extensions[@]} -eq 0 ] || [ -z "$folder" ]; then
        exit_with_message "Error: Missing required parameters. Exiting."
    fi
fi

# Check if the specified folder exists
if [ ! -d "$folder" ]; then
    exit_with_message "Error: The specified folder '$folder' does not exist. Exiting."
fi

# Prepare the find command with dynamic inclusion of file extensions
cmd="find $folder \( -false"
for ext in "${extensions[@]}"; do
    cmd+=" -o -name '*.$ext'"
done
cmd+=" \) -print"

# Run the find command and zip the results
if eval $cmd | zip -@ "${folder}.zip" -x "*/.DS_Store"; then
    echo "${folder}.zip has been created with the specified file types."
else
    exit_with_message "Failed to create zip file. Exiting."
fi
