/*
 *  write runlevel entries into the wtmp.
 *
 *  Copyright (c) 2000 David Parsons. All rights reserved.
 *
 *  This software is released under a berkeley-style copyright; the
 *  details can be found in the file COPYRIGHT.
 */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <utmp.h>
#include <string.h>
#include "init.h"

void
log_runlevel(char current, char last)
{
#define SIZE 5
    static struct utmp wtmp[SIZE];
    static int used = 0;
    struct utmp *wtp = &wtmp[used];

    int wtmpf;

    memset(wtp, 0, sizeof *wtp);

    switch (current) {
    case REBOOT:
    case HALT:	strcpy(wtp->ut_user, "shutdown");
		wtp->ut_pid = 0;
		break;
    case BOOT:	strcpy(wtp->ut_user, "reboot");
		wtp->ut_pid = 0;
		break;
    default:	if (current != last) {
		    strcpy(wtp->ut_user, "runlevel");
		    wtp->ut_pid = (last << 8) | current;
		}
		else
		    return;
    }

    strcpy(wtp->ut_line, "~");
    strcpy(wtp->ut_id, "~~");
    wtp->ut_type = RUN_LVL;
    time( &(wtp->ut_time) );

    if ((wtmpf = open(PREFIX WTMP_FILE, O_WRONLY|O_APPEND)) != -1) {
	write(wtmpf, wtmp, (1+used) * sizeof *wtp);
	used = 0;
	close(wtmpf);
    }
    else if (++used == SIZE) {
	int i;
	for (i = 0; i < SIZE-1; i++)
	    wtmp[i] = wtmp[i+1];
	--used;
    }
} /* log_runlevel */
