#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <err.h>
#include <string.h>
#include <sys/file.h>

#include "tools.h"

void *xmalloc(int size)
{
    void *p;

    p = malloc(size);
    if (!p) {
        fprintf(stderr, "Could not allocate dynamic memory\n");
        exit(1);
    }
    return p;
}

void check_arguments(int argc, const char *program_name)
{
    if (argc < 2) {
        fprintf(stderr, "usage %s <file name>\n", program_name);
        exit(1);
    }
}

int open_file(const char *file_path, int mode)
{
    int fd;

    switch (mode) {
        case 'w':
            fd = open(file_path, O_WRONLY|O_CREAT|O_TRUNC, 0666);
            break;
        case 'e':
            fd = open(file_path, O_WRONLY|O_CREAT|O_EXCL, 0666);
            break;
        case 'm':
            fd = open(file_path, O_RDWR, 0666);
            break;
        case 'r':
            fd = open(file_path, O_RDONLY);
            break;
    }
    if (fd == -1)
        err(1, file_path);

    return fd;
}

void read_data(int fd, int *data)
{
    int rc;

    rc = read(fd, data, sizeof(data));
    if (rc != sizeof(data)) {
        fprintf(stderr, "wrong data read\n");
        exit(1);
    }
}

void modify_data(int fd, int *data, int diff)
{
    int original = data[1];
    data[1] += diff;
    write(fd, &data[1], sizeof(data[1]));
    printf("%d: %d -> %d\n", data[0], original, data[1]);
}

static char *file_lock_str(const char *file_name)
{
    char *file_lock;

    file_lock = xmalloc(strlen(file_name) + 6);
    strcpy(file_lock, file_name);
    strcat(file_lock, ".lock");

    return file_lock;
}

void file_lock(const char *file_path, int sleep_time)
{
    int fd;
    char *file_lock_name = file_lock_str(file_path);

    while (1) {
        fd = open(file_lock_name, O_WRONLY|O_CREAT|O_EXCL, 0666);
        if (fd != -1) {
            close(fd);
            break;
        }
        if (errno != EEXIST)
            err(1, file_lock_name);
        sleep(sleep_time);
    }
    free(file_lock_name);
}

void file_unlock(const char *file_path)
{
    char *file_lock_name = file_lock_str(file_path);
    unlink(file_lock_name);
    free(file_lock_name);
}

static void fcntl_lock(int fd, int type, int size)
{
    struct flock s;
    s.l_type = type;
    s.l_whence = SEEK_SET;
    s.l_start = 0;
    s.l_len = size;
    fcntl(fd, F_SETLKW, &s);
}

void lock(const char *file_name, int fd, int size)
{
#if LOCK == 1
    file_lock(file_name, 1);
#elif LOCK == 2
    flock(fd, LOCK_EX);
#elif LOCK == 3
    lockf(fd, F_LOCK, size);
#elif LOCK == 4
    fcntl_lock(fd, F_WRLCK, size);
#endif
}

void unlock(const char *file_name, int fd, int size)
{
#if LOCK == 1
    file_unlock(file_name);
#elif LOCK == 2
    flock(fd, LOCK_UN);
#elif LOCK == 3
    lockf(fd, F_ULOCK, size);
#elif LOCK == 4
    fcntl_lock(fd, F_UNLCK, size);
#endif
}
