<?php
/**
* Plugin Name: WPDav
* Description: WPDav
* Version: 0.1.3
**/

// Includes
require __DIR__ . '/common.php';
require __DIR__ . '/admin.php';
require __DIR__ . '/plugin-update-checker/plugin-update-checker.php';

YahnisElsts\PluginUpdateChecker\v5\PucFactory::buildUpdateChecker(
    'https://repository.modem.rs/wpdav/wpdav.json',
    __FILE__,
    'wpdav'
);

// Setup REST API
wpdav_setup_wp_rest();

// Add rewrite rule for WebDAV
add_filter("mod_rewrite_rules", function ($rules) {

    $plugin_basename = plugin_basename(__FILE__);

    // If we are deactivating the plugin, do not add the rewrite rule
    if(doing_action('deactivate_' . $plugin_basename)) {
        return $rules;
    }

    $plugin_name = explode('/', $plugin_basename);
    $plugin_name = $plugin_name[0];

    $new_rule =     "# BEGIN wpDAV Rewrite Rule\n";
    $new_rule .=     "<IfModule mod_rewrite.c>\n";
    $new_rule .=    "RewriteRule ^".WPDAV_PLUGIN_REST_PREFIX."/".WPDAV_WEBDAV_ROUTE."/(.*)$ /wp-content/plugins/$plugin_name/webdav.php [QSA,L]\n";
    $new_rule .=    "</IfModule>\n";
    $new_rule .=    "# END wpDAV Rewrite Rule\n";

    return $new_rule . $rules;

});

/**
 * Plugin activation
 */
function wpdav_activate_plugin()
{

    // If token does not exist, create it
    if(!wpdav_get_auth_token()) {
        wpdav_reset_auth_token();
    }

    // Flush the rewrite rules (this will add the WebDAV rewrite rule)
    flush_rewrite_rules();

}
/**
 * Plugin deactivation
 */
function wpdav_deactivate_plugin()
{

    // Flush the rewrite rules (this will remove WebDAV rewrite rule)
    flush_rewrite_rules();

}

/**
 * Plugin uninstall
 */
function wpdav_uninstall_plugin()
{

    // Remove the authentication token
    wpdav_remove_auth_token();

    // Remove the rewrite rule
    flush_rewrite_rules();

}

// Register activation, deactivation and uninstall hooks
register_activation_hook(__FILE__, 'wpdav_activate_plugin');
register_deactivation_hook(__FILE__, 'wpdav_deactivate_plugin');
register_uninstall_hook(__FILE__, 'wpdav_uninstall_plugin');
