/*-
 * Copyright (c) 2004 Free (Olivier Beyssac)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "options.h"
#include "net.h"
#include "client.h"

struct options opt;


int main(int argc, char **argv)
{
  int sd, cmd;
  char *reply, *basename;
  char *host = "localhost";
  char *port = "2905";

  if (argc >= 3)
    host = argv[1];
  if (argc == 4)
    port = argv[2];
      
  if (argc == 1 || argc > 4) {
    fprintf(stderr, "Usage: %s [host [port]] ip\n", argv[0]);
    exit(EXIT_FAILURE);
  }

  if (strlen(argv[argc-1]) > MAX_CMD_LEN - 6) {
    fprintf(stderr, "%s: can't submit data: too long\n", argv[0]);
    exit(EXIT_FAILURE);
  }
  
  if ((basename = strrchr(argv[0], '/')) != NULL)
    basename++;
  else
    basename = argv[0];
  
  if (strcmp(basename, PROGNAME"submit") == 0)
    cmd = CMD_SUBMIT;
  else if (strcmp(basename, PROGNAME"query") == 0)
    cmd = CMD_QUERY;
  else if (strcmp(basename, PROGNAME"insert") == 0)
    cmd = CMD_INSERT;
  else if (strcmp(basename, PROGNAME"decr") == 0)
    cmd = CMD_DECR;
  else {
    fprintf(stderr, "%s: sorry, I don't know what to do\n", argv[0]);
    exit(EXIT_FAILURE);
  }

  options_init(argv[0]);
  opt.log_level = 0;
  
  if ((sd = client_connect(host, port)) == -1)
    fprintf(stderr, "%s: unable to connect to %s:%s\n", argv[0], host, port);
  else if ((reply = client_send_cmdc(sd, cmd, argv[argc-1])) == NULL)
    fprintf(stderr, "%s: error getting server answer\n", argv[0]);
  else
    puts(reply);
  
  close(sd);
  
  exit(EXIT_SUCCESS);
}
