/*
 * asapm is the APM (Advanced Power Management) monitor utility for X Windows
 * Copyright (c) 1998  Albert Dorofeev <Albert@mail.dma.be>
 * For the updates see http://bewoner.dma.be/Albert/linux/
 * 
 * This software is distributed under GPL. For details see LICENSE file.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "state.h"
#include "safecopy.h"

extern struct apm_state state;

char reactions[8][256];
struct reactionPercent {
	unsigned char	used;
	unsigned char	down;
	int	percent;
	char	reaction[255];
}	percent_reactions[10];

void ClearReactions()
{
	memset(reactions, 0, sizeof(reactions));
	memset(percent_reactions, 0, sizeof(percent_reactions));
}

void AddReaction(int order, char * command)
{
	if ( ( order < 0 ) || ( order > 7 ) )
		return;
	safecopy(reactions[order], command, 256);
#ifdef DEBUG
	printf("Reaction[%d] = [%s]\n", order, reactions[order]);
#endif
}

void AddReactionOnPercent(int ifDownTo, int percent, char * command)
{
	int i;
#ifdef DEBUG
	printf("percent reaction [%s %d] = [%s]\n", 
		(ifDownTo ? "down" : "up"), percent, command);
#endif
	for (i = 0; i < 10; ++i)
		if (!percent_reactions[i].used) {
			percent_reactions[i].used = 1;
			percent_reactions[i].down = ifDownTo;
			percent_reactions[i].percent = percent;
			safecopy(percent_reactions[i].reaction,
				command, 256);
			return;
		}
	printf("asapm: Warning! No slot free for [%s]!\n", command);
}

void React()
{
	int i;
	int tmp;

	if ( ! state.flags )
		return;
#ifdef DEBUG
	printf("Reporting APM state change:\n");
#endif
	if (( state.flags & CHANGE_POWER_DOWN ) ||
	    ( state.flags & CHANGE_POWER_UP)) {
	    	tmp = (state.flags & CHANGE_POWER_DOWN) != 0;
		for ( i=0; i<10; ++i ) {
			if ( ( percent_reactions[i].used ) &&
			   ( percent_reactions[i].down == tmp ) &&
			   ( percent_reactions[i].percent == state.percent )) {
#ifdef DEBUG
				printf("[%s %d] [%s]\n", 
					(tmp ? "down" : "up"),
					percent_reactions[i].percent,
					percent_reactions[i].reaction);
#endif
			  	system(percent_reactions[i].reaction);
			}
		}
	}
	for ( i = 0; i < 8; ++i ) {
		if ( state.flags & (1 << i) ) {
#ifdef DEBUG
			printf("[%d] %x [", i, 1 << i);
			state.flags &= ~(1 << i);
#endif
			if ( strlen(reactions[i]) ) {
#ifdef DEBUG
				printf("%s", reactions[i]);
#endif
				system(reactions[i]);
			}
#ifdef DEBUG
			printf("]\n");
#endif
		}
	}

	state.flags = 0;
}



syntax highlighted by Code2HTML, v. 0.9.1