<?xml version='1.0' standalone='yes'?>
<!DOCTYPE PLUGIN [
  <!ENTITY name "webgui-pr-2605">
  <!ENTITY version "2026.04.02.1611">
  <!ENTITY author "unraid">
  <!ENTITY pluginURL "https://preview.dl.unraid.net/pr-plugins/pr-2605/webgui-pr-2605.plg">
  <!ENTITY tarball "webgui-pr-2605-2026.04.02.1611.tar.gz">
  <!ENTITY sha256 "c9b76a64a74828e3edc6333b32e69b95160928e0de6e48497826bddc4fd42912">
  <!ENTITY pr "2605">
  <!ENTITY commit "8aed3b481">
  <!ENTITY github "https://github.com/unraid/webgui">
]>

<PLUGIN name="&name;-&version;" 
        author="&author;" 
        version="&version;" 
        pluginURL="&pluginURL;" 
        min="7.1.0" 
        icon="wrench"
        support="&github;/pull/&pr;">

<CHANGES>
##&version;
- Test build for PR #&pr; (commit &commit;)
- This plugin installs modified files from the PR for testing
- Original files are backed up and restored upon removal
</CHANGES>

<!-- FILE sections run in the listed order - Check if this is an update prior to installing -->

<!-- If this is an update - restore originals before installing the update -->
<FILE Run="/bin/bash" Method="install">
<INLINE>
<![CDATA[
echo "===================================="
echo "WebGUI PR Test Plugin Update"
echo "===================================="
echo "Version: 2026.04.02.1611"
echo ""

BACKUP_DIR="/boot/config/plugins/webgui-pr-2605/backups"
MANIFEST="/boot/config/plugins/webgui-pr-2605/installed_files.txt"

# Ensure required directories exist even on first-time install/update
mkdir -p "/boot/config/plugins/webgui-pr-2605" "$BACKUP_DIR"

# First restore original files to ensure clean state
if [ -f "$MANIFEST" ]; then
    echo "Step 1: Restoring original files before update..."
    echo "------------------------------------------------"
    
    while IFS='|' read -r system_file backup_file; do
        if [ "$backup_file" == "NEW" ]; then
            # This was a new file from previous version, remove it
            if [ -e "$system_file" ] || [ -L "$system_file" ]; then
                echo "Removing PR file: $system_file"
                rm -f "$system_file"
            fi
        else
            # Restore original from backup
            if [ -f "$backup_file" ]; then
                echo "Restoring original: $system_file"
                cp -fp "$backup_file" "$system_file"
            else
                echo "⚠️  Missing backup for: $system_file"
            fi
        fi
    done < "$MANIFEST"
    
    echo ""
    echo "✅ Original files restored"
    echo ""
else
    echo "⚠️  No previous manifest found, proceeding with fresh install"
    echo ""
fi

# Clear the old manifest for the new version (dir now guaranteed)
> "$MANIFEST"

echo "Step 2: Update will now proceed with installation of new PR files..."
echo ""

# The update continues by running the install method which will extract new files
]]>
</INLINE>
</FILE>
<!-- Create backup directory -->
<FILE Run="/bin/bash" Method="install">
<INLINE>
<![CDATA[
echo "===================================="
echo "WebGUI PR Test Plugin Installation"
echo "===================================="
echo "Version: 2026.04.02.1611"
echo "PR: #2605"
echo "Commit: 8aed3b481"
echo ""

# Create directories
mkdir -p /boot/config/plugins/webgui-pr-2605
mkdir -p /boot/config/plugins/webgui-pr-2605/backups

echo "Created plugin directories"
]]>
</INLINE>
</FILE>

<!-- Download tarball from GitHub -->
<FILE Name="/boot/config/plugins/webgui-pr-2605/webgui-pr-2605-2026.04.02.1611.tar.gz">
<URL>https://preview.dl.unraid.net/pr-plugins/pr-2605/webgui-pr-2605-2026.04.02.1611.tar.gz</URL>
<SHA256>&sha256;</SHA256>
</FILE>

<!-- Backup and install files -->
<FILE Run="/bin/bash" Method="install">
<INLINE>
<![CDATA[
BACKUP_DIR="/boot/config/plugins/webgui-pr-2605/backups"
TARBALL="/boot/config/plugins/webgui-pr-2605/webgui-pr-2605-2026.04.02.1611.tar.gz"
MANIFEST="/boot/config/plugins/webgui-pr-2605/installed_files.txt"

echo "Starting file deployment..."
echo "Tarball: $TARBALL"
echo "Backup directory: $BACKUP_DIR"

# Clear manifest
> "$MANIFEST"

# Get file list first
echo "Examining tarball contents..."
tar -tzf "$TARBALL" | head -20
echo ""

# Count total files
FILE_COUNT=$(tar -tzf "$TARBALL" | grep -v '/$' | wc -l)
echo "Total files to process: $FILE_COUNT"
echo ""

# Get file list
tar -tzf "$TARBALL" > /tmp/plugin_files.txt

# Abort if any files are already managed by another PR plugin
OTHER_MANIFESTS="/tmp/pr_plugin_existing_files.txt"
> "$OTHER_MANIFESTS"
for plugin_dir in /boot/config/plugins/webgui-pr-*; do
    if [ ! -d "$plugin_dir" ]; then
        continue
    fi
    if [ "$plugin_dir" == "/boot/config/plugins/webgui-pr-2605" ]; then
        continue
    fi
    manifest="$plugin_dir/installed_files.txt"
    if [ -f "$manifest" ]; then
        plugin_name=$(basename "$plugin_dir")
        while IFS='|' read -r other_file _; do
            if [ -n "$other_file" ]; then
                echo "${other_file}|${plugin_name}" >> "$OTHER_MANIFESTS"
            fi
        done < "$manifest"
    fi
done

if [ -s "$OTHER_MANIFESTS" ]; then
    declare -A existing_files
    while IFS='|' read -r existing_file existing_plugin; do
        if [ -z "$existing_file" ] || [ -z "$existing_plugin" ]; then
            continue
        fi
        if [ -n "${existing_files[$existing_file]:-}" ]; then
            if [[ ",${existing_files[$existing_file]}," != *",${existing_plugin},"* ]]; then
                existing_files[$existing_file]="${existing_files[$existing_file]},${existing_plugin}"
            fi
        else
            existing_files[$existing_file]="$existing_plugin"
        fi
    done < "$OTHER_MANIFESTS"

    conflict_found=0
    declare -A conflict_plugins
    while IFS= read -r file; do
        # Skip directories
        if [[ "$file" == */ ]]; then
            continue
        fi

        system_file="/${file}"
        if [ -n "${existing_files[$system_file]:-}" ]; then
            conflict_found=1
            echo "Conflict: $system_file is already managed by ${existing_files[$system_file]}"
            IFS=',' read -r -a plugin_list <<< "${existing_files[$system_file]}"
            for plugin in "${plugin_list[@]}"; do
                conflict_plugins[$plugin]=1
            done
        fi
    done < /tmp/plugin_files.txt

    if [ "$conflict_found" -eq 1 ]; then
        echo ""
        echo "❌ Install aborted."
        echo "One or more files are already managed by another PR plugin."
        echo "Please uninstall the conflicting plugin(s) and try again:"
        for plugin in "${!conflict_plugins[@]}"; do
            echo "  plugin remove ${plugin}.plg"
        done
        rm -f "$OTHER_MANIFESTS" /tmp/plugin_files.txt
        exit 1
    fi
fi

rm -f "$OTHER_MANIFESTS"

# Backup original files BEFORE extraction
while IFS= read -r file; do
    # Skip directories
    if [[ "$file" == */ ]]; then
        continue
    fi
    
    # The tarball contains usr/local/emhttp/... (no leading slash)
    # When we extract with -C /, it becomes /usr/local/emhttp/...
    SYSTEM_FILE="/${file}"
    BACKUP_FILE="$BACKUP_DIR/$(echo "$file" | tr '/' '_')"
    
    echo "Processing: $file"
    
    # Only backup if we haven't already backed up this file
    # (preserves original backups across updates)
    if [ -f "$BACKUP_FILE" ]; then
        echo "  → Using existing backup: $BACKUP_FILE"
        echo "$SYSTEM_FILE|$BACKUP_FILE" >> "$MANIFEST"
    elif [ -f "$SYSTEM_FILE" ]; then
        echo "  → Creating backup of original: $SYSTEM_FILE"
        cp -p "$SYSTEM_FILE" "$BACKUP_FILE"
        echo "$SYSTEM_FILE|$BACKUP_FILE" >> "$MANIFEST"
    else
        echo "  → Will create new: $SYSTEM_FILE"
        echo "$SYSTEM_FILE|NEW" >> "$MANIFEST"
    fi
done < /tmp/plugin_files.txt

# Clean up temp file
rm -f /tmp/plugin_files.txt

# Extract the tarball to root with verbose output
# Since tarball contains usr/local/emhttp/..., extracting to / makes it /usr/local/emhttp/...
echo ""
echo "Extracting files to system (verbose mode)..."
echo "----------------------------------------"
tar -xzvf "$TARBALL" -C /
EXTRACT_STATUS=$?
echo "----------------------------------------"
echo "Extraction completed with status: $EXTRACT_STATUS"
echo ""

# Verify extraction
echo "Verifying installation..."
INSTALLED_COUNT=0
while IFS='|' read -r file backup; do
    if [ -f "$file" ]; then
        INSTALLED_COUNT=$((INSTALLED_COUNT + 1))
    fi
done < "$MANIFEST"

echo "Successfully installed $INSTALLED_COUNT files"

echo ""
echo "✅ Installation complete!"
echo ""
echo "Summary:"
echo "--------"
echo "Files deployed: $INSTALLED_COUNT"
echo ""
if [ $INSTALLED_COUNT -gt 0 ]; then
    echo "Modified files:"
    while IFS='|' read -r file backup; do
        if [ -f "$file" ]; then
            if [ "$backup" == "NEW" ]; then
                echo "  [NEW] $file"
            else
                echo "  [MOD] $file"
            fi
        fi
    done < "$MANIFEST"
else
    echo "⚠️  WARNING: No files were installed!"
    echo "Check that the tarball structure matches the expected format."
fi

echo ""
echo "⚠️  This is a TEST plugin for PR #2605"
echo "⚠️  Remove this plugin before applying production updates"
echo ""
echo "⚠️  NOTE: Under certain circumstances, it might be necessary to reboot the server for the code changes to take effect"
]]>
</INLINE>
</FILE>

<!-- Add a banner to warn user this plugin is installed -->
<FILE Name="/usr/local/emhttp/plugins/webgui-pr-2605/Banner-2605.page">
<INLINE>
<![CDATA[
Menu='Buttons'
Link='nav-user'
---
<script>
  $(function() {
    // Check for updates (non-dismissible)
    caPluginUpdateCheck("webgui-pr-2605.plg", {noDismiss: true},function(result){
      try {
        let json = JSON.parse(result);
        if ( ! json.version ) {
          addBannerWarning("Note: webgui-pr-2605 has either been merged or removed");
        }
      } catch(e) {}
    });

    // Create banner with uninstall link (nondismissible)
    let bannerMessage = "Modified GUI installed via <b>webgui-pr-2605</b> plugin. " +
                       "<a onclick='uninstallPRPlugin()' style='cursor: pointer; text-decoration: underline;'>Click here to uninstall</a>";

    // true = warning style, true = non-dismissible
    addBannerWarning(bannerMessage, true, true);

    // Define uninstall function
    window.uninstallPRPlugin = function() {
      swal({
        title: "Uninstall PR Test Plugin?",
        text: "This will restore all original files and remove the test plugin.",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "Yes, uninstall",
        cancelButtonText: "Cancel",
        closeOnConfirm: false,
        showLoaderOnConfirm: true
      }, function(isConfirm) {
        if (isConfirm) {
          // Execute plugin removal using openPlugin (Unraid's standard method)
          // The "refresh" parameter will automatically reload the page when uninstall is completed
          openPlugin("plugin remove webgui-pr-2605.plg", "Removing PR Test Plugin", "", "refresh");
        }
      });
    };
  });
</script>
]]>
</INLINE>
</FILE>

<!-- Removal script -->
<FILE Run="/bin/bash" Method="remove">
<INLINE>
<![CDATA[
echo "===================================="
echo "WebGUI PR Test Plugin Removal"
echo "===================================="
echo ""

BACKUP_DIR="/boot/config/plugins/webgui-pr-2605/backups"
MANIFEST="/boot/config/plugins/webgui-pr-2605/installed_files.txt"

if [ -f "$MANIFEST" ]; then
    echo "Restoring original files..."
    
    while IFS='|' read -r system_file backup_file; do
        if [ "$backup_file" == "NEW" ]; then
            # This was a new file, remove it
            if [ -e "$system_file" ] || [ -L "$system_file" ]; then
                echo "Removing new file: $system_file"
                rm -f "$system_file"
            fi
        else
            # Restore from backup
            if [ -f "$backup_file" ]; then
                echo "Restoring: $system_file"
                cp -fp "$backup_file" "$system_file"
            else
                echo "⚠️  Missing backup for: $system_file"
            fi
        fi
    done < "$MANIFEST"
    
    echo ""
    echo "✅ Original files restored"
else
    echo "⚠️  No manifest found, cannot restore files"
fi

# Clean up
echo "Cleaning up plugin files..."
# Remove the banner
rm -rf "/usr/local/emhttp/plugins/webgui-pr-2605"
# Remove the plugin directory (which includes the tarball and backups)
rm -rf "/boot/config/plugins/webgui-pr-2605"
# Note: The .plg file is handled automatically by the plugin system and should not be removed here

echo ""
echo "✅ Plugin removed successfully"
echo ""
echo "⚠️  A reboot of the server might be required under certain circumstances to completely remove all traces of this plugin"
]]>
</INLINE>
</FILE>

</PLUGIN>
