#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <string.h>
#include <time.h>

#include "spasm.h"
#include "dbfunc.h"

void spasm_error(int syslevel, char *errstr, ...) {
    va_list arglist;

    va_start(arglist, errstr);
    vfprintf(stderr, errstr, arglist);
    fprintf(stderr, "\n");      /* spasm_error args aren't terminated by \n */
    va_end(arglist);
}

int main(int argc, char **argv) {
    char *src;
    char *dest;
    struct flock lockinfo;
    int fd;

    if(argv[1] == NULL) exit(1);
    if((src = sp_strcat(LOG_DIRECTORY, argv[1])) == NULL) {
	fprintf(stderr, "Error allocating memory for src\n");
    }
    if((dest = calloc(strlen(LOG_ARCHIVE_DIR)+sizeof(time_t)+sizeof(pid_t)+5, 1)) == NULL) {
	fprintf(stderr, "Error allocating memory for destination: %m\n");
	free(src);
	exit(1);
    }
    sprintf(dest, "%s/%lu-%d", LOG_ARCHIVE_DIR, time(NULL), getpid());
    /* lock file to prevent corruption */
    if((fd = open(src, O_RDWR)) == -1) {
	fprintf(stderr, "Error opening logfile: %m\n");
	exit(1);
    }
    memset(&lockinfo, 0, sizeof(lockinfo));
    lockinfo.l_type = F_WRLCK;
    if(fcntl(fd, F_SETLKW, &lockinfo) == -1) {
	fprintf(stderr, "Error locking logfile: %m\n");
	close(fd);
	exit(1);
    }
    rename(src, dest);
    close(fd);
    free(src);
    free(dest);
    exit(0);
}
