/****************************************************************
 *                                                              *
 *  LIBDIST V1.0						*
 *                                                              *
 *  elec-test.c -- test election algorithm                      *
 *                                                              *
 *  Last changed: 19.02.96                                      *
 *  Author: Frank Kargl (frank.kargl@informatik.uni-ulm.de)     *
 *                                                              *
 *  Restrictions: works only for Solaris 2.6 or above           *
 *                                                              *
 ****************************************************************/

#include "libdist.h"
#include "config.h"
#include "ctype.h"

#include <arpa/inet.h>

/* what election port to use */
#define PORT "4711"

void ausgabe(char *winner,int port,int myport) {

    struct sockaddr_in *sin_ptr;

    sin_ptr=dl_sck_getifadr();

    printf("\nThe Winner is ... Heeeenryyy Maaaaske # %s, %u, %u\n",winner,port,myport);

    if ( !strcmp(winner,inet_ntoa(sin_ptr->sin_addr)) &&
	  port==myport) {
	printf("\nHurraaa ... I'm the Winner !!!\n");
    }
}

int main(int argc, char **argv) {

    thread_t tid;
    int ret;
    char input[80];
    int tmpsock;

    printf("Election - time ... geeet reeeaadyyy toooo ruuuumble ;-)\n\n");
    printf("Use <S> to start an election\n");
    printf("Use <Q> to quit\n");
    printf("All other input is broadcasted as is\n\n");

    tid = dl_el_startserver(PORT,ausgabe);
    printf("dl_el_startserver returned %d\n",tid);

    while(1) {

	sleep(1);
	puts("> ");
	gets(input);
	if ( input[0] == 'S' ) {
	    ret = dl_el_startele(PORT);
	    printf("dl_el_startele returned %d\n",ret);
	    continue;
	}

	if ( input[0] == 'Q' ) {
	    printf("Exiting\n");
	    ret = dl_el_stopserver(tid);
	    printf("dl_el_stopserver returned %d\n",ret);
	    sleep(5);
	    exit(1);
	}

	if ( isalpha((int)input[0]) ) {
	    tmpsock=dl_sck_sockb();
	    dl_sck_sendb(tmpsock,PORT,input);
	    dl_sck_close(tmpsock);
	}
    }
}
