#!/bin/bash

# Define the plugin names and paths
PLUGINS=("eveai-chat" "eveai_sync")
RELEASE_PATH="/Volumes/OWC4M2_1/Dropbox/Professioneel/AskEveAI/Production Plugins/WordPress"

# Helper function: Print usage
print_usage() {
    echo "Usage: $0 [-b | -r] [plugin_name...]"
    echo "  -b      Build only"
    echo "  -r      Release only"
    echo "  If no options are provided, both build and release will be performed."
    echo "  Specify plugin names to target specific plugins. Default is all."
}

# Build function
build_plugin() {
    local plugin=$1
    local zip_file="${plugin}.zip"

    echo "Building plugin: $plugin"
    if [ -f "$zip_file" ]; then
        echo "Removing existing zip file: $zip_file"
        rm "$zip_file"
    fi

    if [ -d "$plugin" ]; then
        zip -r "$zip_file" "$plugin" > /dev/null
        echo "Plugin $plugin built successfully: $zip_file"
    else
        echo "Error: Plugin folder $plugin does not exist. Skipping."
    fi
}

# Release function
release_plugin() {
    local plugin=$1
    local zip_file="${plugin}.zip"
    local destination="$RELEASE_PATH/$zip_file"

    echo "Releasing plugin: $plugin"
    if [ -f "$zip_file" ]; then
        cp "$zip_file" "$RELEASE_PATH"
        echo "Plugin $plugin released successfully to $destination"
    else
        echo "Error: Build file $zip_file not found. Please build the plugin first."
    fi
}

# Parse arguments
BUILD=false
RELEASE=false
TARGET_PLUGINS=("${PLUGINS[@]}")

while getopts "brh" opt; do
    case "$opt" in
        b) BUILD=true ;;
        r) RELEASE=true ;;
        h) print_usage; exit 0 ;;
        *) print_usage; exit 1 ;;
    esac
done
shift $((OPTIND-1))

# Handle plugin name filtering
if [ "$#" -gt 0 ]; then
    TARGET_PLUGINS=("$@")
fi

# Default action: both build and release
if ! $BUILD && ! $RELEASE; then
    BUILD=true
    RELEASE=true
fi

# Execute actions
for plugin in "${TARGET_PLUGINS[@]}"; do
    if $BUILD; then
        build_plugin "$plugin"
    fi
    if $RELEASE; then
        release_plugin "$plugin"
    fi
done