#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>

void send_cmd(char *sockname, char *cmd)
{
    int                 sock;
    struct sockaddr_un  addr;
    int                 total, tbw;

    fprintf(stderr, "sending '%s' on '%s'\n", cmd, sockname);

    if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
    {
        perror("socket");
        exit(1);
    }

    addr.sun_family = AF_UNIX;
    strcpy(addr.sun_path, sockname);

    if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
    {
        perror("connect");
        exit(1);
    }

    total = strlen(cmd);
    tbw = 0;
    while (tbw < total)
    {
        int bw;
        if ((bw = write(sock, cmd + tbw, total - tbw)) < 0)
        {
            switch (errno)
            {
            case EAGAIN:
            case EINTR:
                continue;

            default:
                close(sock);
                perror("socket");
                exit(1);
            }
        }
        tbw += bw;
    }

    close(sock);
    return;
}

int
main(int argc, char **argv)
{
    if (argc != 3)
    {
        fprintf(stderr, "usage: lw-ctl <control file> <command>\n"
                "\tcommand be one of:\n"
                "\tRUN: put loadwatch into sticky run mode\n"
                "\tSTOP: put loadwatch into sticky stop mode\n"
                "\tWATCH: put loadwatch into regular load watching mode\n");
    }
    else
    {
        send_cmd(argv[1], argv[2]);
    }
}
