#include <sys/io.h>
#include <stdbool.h>
#include <unistd.h>

#include "yasnd-log.h"

bool lpt_enable=false; // control usage of LPT port to reset target devices
int lpt_port=0x378; // LPT port in hex(0x378 is usually LPT1)

/*
	Function, that turn off all LPT port pins.
	This is needed to unlock LPT control circuit, when
	management computer is just booted
*/
void lpt_init()
{
	if (lpt_enable)
	{
		if (ioperm (lpt_port, 3, 1))
		{
			log_event("Error: Unlocking the circuit fails due to LPT port access error");
			// disable LPT port usage
			lpt_enable=false;
			return;
		}
		// Unlock circuit
		outb (0, lpt_port);
	}
}

/*
	Function, that turn on first LPT port pin and turn off others.
	This is needed to lock LPT control circuit, when
	management computer is rebooted
*/
void lpt_lock_cond(bool ignore_options)
{
	if (lpt_enable || ignore_options)
	{
		if (ioperm (lpt_port, 3, 1))
		{
			log_event("Error: Locking the circuit fails due to LPT port access error");
			// disable LPT port usage
			lpt_enable=false;
			return;
		}
		// Lock circuit
		outb (1, lpt_port);
	}
}

/*
	Function, that turn on only one LPT port pin, defined by it argument, wait a second,
	and turn off all pins. That is enough to reset specified host.
*/
void reset_pin(int pin_num)
{
	if (lpt_enable)
	{
		if (pin_num==0)
			return; // there is no LPT control for target host
		if (pin_num<2 || pin_num>8)
		{
			log_event("Error: incorrent LPT pin number");
			return;
		}
		int pins = 1<<(pin_num-1);
		if (ioperm (lpt_port, 3, 1))
		{
			log_event("Error: LPT port access error");
			return;
		}
		// Reset host
		outb (pins, lpt_port);
		sleep(1);
		outb (0, lpt_port);
	}
}