#!/usr/bin/php
<?php
/**
 * dtweb - Device Tree editor for UDOO boards
 * Copyright (C) 2015 Francesco Montefoschi <francesco.monte@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @package dtweb
 * @author  Francesco Montefoschi
 * @license http://www.gnu.org/licenses/gpl-3.0.html  GNU GPL 3.0
 */
 
require "/opt/dtweb/webapp/autoloader.php";

class UdooM4Ctl
{
    const ERROR_WRONG_USAGE = 1;
    const ERROR_RUN_SUPERUSER = 2;
    const ERROR_BOARD_UNSUPPORTED = 3;
    
    public function __construct()
    {
        if (posix_geteuid() != 0) {
            echo "This program must be run as root." . PHP_EOL;
            exit(self::ERROR_RUN_SUPERUSER);
        }

        $board = Service_BoardDetector::boardFromModel();
        if ($board == 'qdl') {
            echo "This board is unsupported." . PHP_EOL;
            exit(self::ERROR_BOARD_UNSUPPORTED);
        }
    }
    
    public function show_usage() {
        echo "Use this tool to enable or disable the M4 core." . PHP_EOL . PHP_EOL;
        echo "Usage: udoom4ctl disable" . PHP_EOL;
        echo "       udoom4ctl enable" . PHP_EOL;
        echo "       udoom4ctl status" . PHP_EOL;
        exit(self::ERROR_WRONG_USAGE);
    }
    
    public function __invoke()
    {
        if ($_SERVER['argc'] != 2) {
            $this->show_usage();
        }

        $uenvEditor = new Service_UenvEditor();

        $argument = $_SERVER['argv'][1];
        switch ($argument) {
            case 'disable':
                $uenvEditor->setEnv("m4_enabled", "false");
                $uenvEditor->toFile();
                break;
                
            case 'enable':
                $uenvEditor->setEnv("m4_enabled", "true");
                $uenvEditor->toFile();
                break;
                
            case 'status':
                echo $uenvEditor->getEnv("m4_enabled", "true") . PHP_EOL;
                break;
            
            default:
                $this->show_usage();
        }

        exit(0);
    }
}

$command = new UdooM4Ctl();
$command();
