/*
 * Copyright (c) 2019 Clementine Computing LLC.
 *
 * This file is part of PopuFare.
 * 
 * PopuFare is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * PopuFare is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with PopuFare.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "../common/common_defs.h"
#include "../commhub/commhub.h"

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

    int fd;
    char foo[1024];
    char *bar;
    struct message_record msg;
    int retval, i;

    fd = connect_to_message_server(argv[0]);

    if(fd < 0)
    {
        fprintf(stderr,"Cannot connect to IPC server!\n");
        exit(1);
    }

    while(!feof(stdin))
    {
        bar = fgets(foo, sizeof(foo), stdin);
        
        if(bar == NULL)
            break;
    
                
        for(i = 0; i < 1024; i++)
        {
            if(foo[i] == '\0')
                break;
        
            if( (foo[i] == '\r') ||(foo[i] == '\n') )
            {
                foo[i] = '\0';
                break;
            }
        }
        
        prepare_message(&msg, MAILBOX_TOKEN_MAG, foo, i);
        retval = send_message(fd, &msg);
        
        if(retval < 0)
        {
            fprintf(stderr, "Error attempting to send message!\n");
            exit(2);
        }
        
    }    

    return 0;
}


