#!/bin/bash

# Function to display usage
usage() {
    echo "Usage: $0 -s /path/to/source -t /path/to/target"
    echo "  -s    Source Moodle installation directory"
    echo "  -t    Target Moodle installation directory"
    exit 1
}

# Parse named parameters using getopts
while getopts "s:t:" opt; do
    case $opt in
        s) SOURCE_DIR="$optarg" ;;
        t) TARGET_DIR="$optarg" ;;
        *) usage ;;
    esac
done

# Validation of inputs
if [[ -z "$SOURCE_DIR" || -z "$TARGET_DIR" ]]; then
    usage
fi

if [[ ! -d "$SOURCE_DIR" || ! -d "$TARGET_DIR" ]]; then
    echo "Error: Source or Target directory does not exist."
    exit 1
fi

echo "--- Starting Moodle Migration Process ---"

# 1. Ownership Identification
if [[ -f "$SOURCE_DIR/config.php" ]]; then
    FILE_OWNER=$(stat -c '%U' "$SOURCE_DIR/config.php")
    FILE_GROUP=$(stat -c '%G' "$SOURCE_DIR/config.php")
    echo "Detected source owner: $FILE_OWNER:$FILE_GROUP"
    
    echo "Copying config.php..."
    cp "$SOURCE_DIR/config.php" "$TARGET_DIR/config.php"
else
    echo "Warning: config.php not found in source."
fi

# 2. Comprehensive Plugin Locations with Functional Descriptions
# These paths cover the entirety of Moodle's extensible subsystems.
PLUGIN_LOCATIONS=(
    "admin/report"              # Site-wide administration reports
    "admin/tool"                # Administrative utilities (e.g., bulk user upload)
    "auth"                      # Authentication methods (LDAP, OAuth2, etc.)
    "availability/condition"    # Restrict access logic (conditional availability)
    "blocks"                    # UI widgets appearing on page sidebars
    "cache/stores"              # Caching backends (Redis, Memcached)
    "cache/lock"                # Cache locking mechanisms
    "calendartype"              # Calendar systems (Gregorian, Hijri, etc.)
    "contentbank"               # Content bank asset handlers (H5P, etc.)
    "course/format"             # Visual layout of courses (Grid, Topics, etc.)
    "dataformat"                # Export formats for data (CSV, Excel, ODS)
    "enrol"                     # Course enrollment methods (Manual, Self, PayPal)
    "filter"                    # Text processing filters (MathJax, Multimedia)
    "grade/export"              # Gradebook export formats
    "grade/import"              # Gradebook import methods
    "grade/report"              # Gradebook visual reports
    "gradingform"               # Advanced grading (Rubrics, Marking Guides)
    "groupbase"                 # Core group management extensions
    "lib/editor/atto/plugins"   # Atto HTML editor extensions
    "lib/editor/tiny/plugins"   # TinyMCE HTML editor extensions
    "local"                     # General-purpose custom plugins/hacks
    "media/player"              # Multimedia playback handlers (VideoJS, etc.)
    "message"                   # Messaging outputs (Email, Mobile Push)
    "mod"                       # Primary activities (Quiz, Assignment, Forum)
    "mod/assign/submission"     # Assignment submission types (File, Online Text)
    "mod/assign/feedback"       # Assignment feedback types (PDF Annotation)
    "mod/book/tool"             # Book activity utilities (Import/Export)
    "mod/data/field"            # Database activity field types
    "mod/feedback/item"         # Feedback activity question types
    "mod/quiz/accessrule"       # Quiz entry constraints (Password, IP, SEB)
    "mod/quiz/report"           # Specialized quiz attempt analytics
    "mod/workshop/allocation"   # Workshop peer-review allocation logic
    "paygw"                     # Payment gateway integrations
    "plagiarism"                # Plagiarism detection services (Turnitin, etc.)
    "portfolio"                 # External portfolio export destinations
    "question/behaviour"        # Logic for how questions interact with users
    "question/format"           # Question bank import/export formats
    "question/type"             # Specific question types (Multiple Choice, etc.)
    "report"                    # General course or site reports
    "repository"                # External file sources (Google Drive, OneDrive)
    "theme"                     # Look and feel (CSS, Mustache templates)
    "user/profile/field"        # Custom user profile data types
    "customfield/field"         # Custom field types for courses/categories
    "webservice"                # External API protocols (REST, SOAP)
)

# 3. Execution of File Transfer
for LOCATION in "${PLUGIN_LOCATIONS[@]}"; do
    SRC_PATH="$SOURCE_DIR/$LOCATION"
    TGT_PATH="$TARGET_DIR/$LOCATION"

    if [[ -d "$SRC_PATH" ]]; then
        mkdir -p "$TGT_PATH"
        for DIR in "$SRC_PATH"/*/; do
            [ -e "$DIR" ] || continue
            PLUGIN_NAME=$(basename "$DIR")
            
            # Additional plugin identification logic
            if [[ ! -d "$TGT_PATH/$PLUGIN_NAME" ]]; then
                echo "Deploying extension: $LOCATION/$PLUGIN_NAME"
                cp -R "$DIR" "$TGT_PATH/"
            fi
        done
    fi
done

# 4. Final Permission Alignment
if [[ -n "$FILE_OWNER" ]]; then
    echo "Finalizing ownership: Setting $TARGET_DIR to $FILE_OWNER:$FILE_GROUP"
    chown -R "$FILE_OWNER:$FILE_GROUP" "$TARGET_DIR"
fi

echo "--- Migration Complete ---"