/*
 * power.c
 *
 * Copyright (C) 2016 Aleksandar Andrejevic <theflash@sdf.lonestar.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <power.h>
#include <syscalls.h>
#include <user.h>
#include <cpu.h>

static power_callbacks_t *power_callbacks = NULL;

dword_t register_power_callbacks(power_callbacks_t *callbacks)
{
    if (callbacks && power_callbacks) return ERR_EXISTS;
    power_callbacks = callbacks;
    return ERR_SUCCESS;
}

sysret_t syscall_power_control(power_command_t command)
{
    if (get_previous_mode() == USER_MODE && !check_privileges(PRIVILEGE_POWER_CONTROL))
    {
        return ERR_FORBIDDEN;
    }

    switch (command)
    {
    case POWER_COMMAND_SHUTDOWN:
        if (power_callbacks) power_callbacks->set_state(POWER_STATE_OFF);

    case POWER_COMMAND_HALT:
        cpu_disable_interrupts();
        cpu_halt();
        break;

    case POWER_COMMAND_REBOOT:
        cpu_disable_interrupts();
        while (cpu_read_port_byte(0x64) & 0x02) continue;
        cpu_write_port_byte(0x64, 0xFE);
        cpu_halt();
        break;

    default:
        return ERR_INVALID;
    }

    return ERR_SUCCESS;
}
