#!/bin/bash
################################################################################
# WordPress.org Plugin Package Builder
# 
# Creates a clean distribution package for WordPress.org submission
# Excludes development files using .distignore patterns
#
# Usage: ./build-package.sh [version]
# Example: ./build-package.sh 1.0.4
################################################################################

set -e  # Exit on error

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Plugin details
PLUGIN_SLUG="comments-press-zone"
PLUGIN_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUILD_DIR="${PLUGIN_DIR}/build"
DIST_DIR="${BUILD_DIR}/dist"

# Version from argument or extract from main plugin file
VERSION=${1:-$(grep "Version:" "${PLUGIN_DIR}/${PLUGIN_SLUG}.php" | awk '{print $2}')}

# Package output
PACKAGE_NAME="${PLUGIN_SLUG}-${VERSION}.zip"
PACKAGE_PATH="${BUILD_DIR}/${PACKAGE_NAME}"

################################################################################
# Functions
################################################################################

print_header() {
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${BLUE}  WordPress.org Package Builder${NC}"
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
}

print_step() {
    echo -e "${YELLOW}▶${NC} $1"
}

print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

check_distignore() {
    if [ ! -f "${PLUGIN_DIR}/.distignore" ]; then
        print_error ".distignore file not found!"
        echo "Creating default .distignore file..."
        cat > "${PLUGIN_DIR}/.distignore" << 'EOF'
.git
.gitignore
.distignore
.idea
.vscode
.DS_Store
build-package.sh
node_modules
tests
tmp
*.log
.github
EOF
        print_success "Created .distignore with default patterns"
    fi
}

clean_build_dir() {
    print_step "Cleaning build directory..."
    rm -rf "${BUILD_DIR}"
    mkdir -p "${DIST_DIR}"
    print_success "Build directory cleaned"
}

copy_files() {
    print_step "Copying plugin files..."
    
    # Copy everything first
    rsync -av --exclude-from="${PLUGIN_DIR}/.distignore" \
        "${PLUGIN_DIR}/" \
        "${DIST_DIR}/${PLUGIN_SLUG}/" \
        --exclude='build' \
        --quiet
    
    print_success "Files copied to dist directory"
}

verify_required_files() {
    print_step "Verifying required files..."
    
    local required_files=(
        "${PLUGIN_SLUG}.php"
        "readme.txt"
    )
    
    local missing=0
    for file in "${required_files[@]}"; do
        if [ ! -f "${DIST_DIR}/${PLUGIN_SLUG}/${file}" ]; then
            print_error "Missing required file: ${file}"
            missing=$((missing + 1))
        fi
    done
    
    if [ $missing -gt 0 ]; then
        print_error "Package build failed: missing required files"
        exit 1
    fi
    
    print_success "All required files present"
}

show_package_contents() {
    print_step "Package contents:"
    echo ""
    tree -L 2 -I 'node_modules' "${DIST_DIR}/${PLUGIN_SLUG}" 2>/dev/null || \
    find "${DIST_DIR}/${PLUGIN_SLUG}" -maxdepth 2 -type f | sed 's|'"${DIST_DIR}/${PLUGIN_SLUG}"'||' | sort
    echo ""
}

create_zip() {
    print_step "Creating ZIP package..."
    
    cd "${DIST_DIR}"
    zip -r "${PACKAGE_PATH}" "${PLUGIN_SLUG}" -q
    cd "${PLUGIN_DIR}"
    
    print_success "Package created: ${PACKAGE_PATH}"
}

show_summary() {
    local size=$(du -h "${PACKAGE_PATH}" | cut -f1)
    
    echo ""
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}  Package Build Complete!${NC}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
    echo -e "  Plugin:   ${BLUE}${PLUGIN_SLUG}${NC}"
    echo -e "  Version:  ${BLUE}${VERSION}${NC}"
    echo -e "  Package:  ${BLUE}${PACKAGE_NAME}${NC}"
    echo -e "  Size:     ${BLUE}${size}${NC}"
    echo -e "  Location: ${BLUE}${PACKAGE_PATH}${NC}"
    echo ""
    echo -e "${YELLOW}Next steps:${NC}"
    echo "  1. Test the package: unzip and test in clean WordPress install"
    echo "  2. Upload to WordPress.org: https://wordpress.org/plugins/developers/add/"
    echo ""
}

################################################################################
# Main execution
################################################################################

main() {
    print_header
    
    echo "Plugin: ${PLUGIN_SLUG}"
    echo "Version: ${VERSION}"
    echo ""
    
    check_distignore
    clean_build_dir
    copy_files
    verify_required_files
    show_package_contents
    create_zip
    show_summary
}

# Run main function
main "$@"
