<?php
/**
 * Plugin Name: AuctionForge Keepalive
 * Description: Auto-reactivates AuctionForge if a failed plugin update or
 *   misbehaving theme has dropped it from active_plugins. Lives in
 *   wp-content/mu-plugins/ — WordPress can't deactivate must-use plugins,
 *   so this watchdog keeps running even when AF itself has been knocked
 *   out by a bad release.
 *
 *   Smoke-checks the Plugin Name header before reactivation so a genuinely
 *   corrupt AF file doesn't fatal-loop the site. Records markers
 *   (auctionforge_auto_reactivated_at, _count, _failed_at) that the AF
 *   sync stream picks up so wpdeploy sees what happened.
 *
 *   Installed automatically by AuctionForge ≥ 3.7.0.4 — do not edit by
 *   hand; AF will overwrite this file when its version of the keepalive
 *   bumps. Keep KEEPALIVE_VERSION below in sync with the source template.
 *
 * Author: SmoothByte IT
 * Version: 1.0.0
 *
 * KEEPALIVE_VERSION: 1.0.0
 */

if (!defined('ABSPATH')) exit;

add_action('plugins_loaded', function () {
    // Already loaded? Nothing to do.
    if (defined('AUCTIONFORGE_VERSION') || class_exists('\auctionforge\inc\controllers\BidspiritLots', false)) {
        return;
    }

    $expected = 'auctionforge/auctionforge.php';
    $plugin_dir = defined('WP_PLUGIN_DIR') ? WP_PLUGIN_DIR : ABSPATH . 'wp-content/plugins';
    $path = $plugin_dir . '/' . $expected;

    if (!file_exists($path)) return;

    $active = (array) get_option('active_plugins', []);
    if (in_array($expected, $active, true)) return;

    $head = @file_get_contents($path, false, null, 0, 4096);
    if ($head === false || stripos($head, 'Plugin Name:') === false) {
        update_option('auctionforge_auto_reactivated_failed_at', current_time('mysql', true), 'no');
        return;
    }

    $active[] = $expected;
    sort($active);
    update_option('active_plugins', array_values(array_unique($active)));

    update_option('auctionforge_auto_reactivated_at', current_time('mysql', true), 'no');
    update_option('auctionforge_auto_reactivated_count',
        ((int) get_option('auctionforge_auto_reactivated_count', 0)) + 1, 'no');

    if (file_exists($path)) {
        include_once $path;
    }
}, 1);
