<?php
namespace Grav\Plugin;

use Grav\Common\Page\Page;
use Grav\Common\Plugin;

/**
 * Features:
 * - /sync   Cheap git-sync (did not knew about it at the time)
 *
 * Class M3P2Plugin
 * @package Grav\Plugin
 */
class M3P2Plugin extends Plugin
{
    /**
     * @return array
     *
     * The getSubscribedEvents() gives the core a list of events
     *     that the plugin wants to listen to. The key of each
     *     array section is the event that the plugin listens to
     *     and the value (in the form of an array) contains the
     *     callable (or function) as well as the priority. The
     *     higher the number the higher the priority.
     */
    public static function getSubscribedEvents()
    {
        return [
            'onPluginsInitialized' => ['onPluginsInitialized', 0]
        ];
    }

    /**
     * Initialize the plugin
     */
    public function onPluginsInitialized()
    {
        // Don't proceed if we are in the admin plugin
        if ($this->isAdmin()) {
            return;
        }

        $uri = $this->grav['uri'];
        $route = $this->config->get('plugins.m3-p2.route');
//        throw new \Exception($route." - ".$uri->path());

        if ($route && $route == $uri->path()) {
            $this->enable([
                'onPageInitialized' => ['onPageInitialized', 0]
            ]);
        }
    }

    /**
     * Send user to a random page
     */
    public function onPageInitialized()
    {
        $out = "Trying to sync content with GitLab…\n";

        # shell pwd is project root
        $out .= shell_exec("cd user/pages && git pull --rebase --autostash origin master 2>&1") . "\n";
        $out .= shell_exec("fortune") . "\n";
        //$out .= shell_exec("fortune | cowsay -e Oø -f dragon") . "\n";

        $out .= "Done.";

        die("<pre>".$out."</pre>");  // This is all I find to write to the page.
    }
}
