/**************************/
/* CLARiiON SPS Simulator */
/* control program        */
/*                        */
/* Derek Konigsberg       */
/**************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "spsd.h"

int dflag;

int valid_msg(char msg)
{
  if((msg=='0')||(msg=='1')||(msg=='2'))
    return 1;
  else
    return 0;
}

void send_message(char *sname, char msg)
{
  int sock;
  struct sockaddr_un saddr, caddr;
  char sbuf[1];
  saddr.sun_family=AF_UNIX;
  strcpy(saddr.sun_path, sname);
  caddr.sun_family=AF_UNIX;
  sock = socket(AF_UNIX, SOCK_DGRAM, 0);
  bind(sock, (struct sockaddr *)&caddr, sizeof(caddr));
  if(connect(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
    printf("spsctl: Error connecting to socket\n");
    return;
  }
  sbuf[0]=msg;
  write(sock, sbuf, 1);
  close(sock);
}

void usage(char *pname)
{
  printf("Usage: %s [options]\n", pname);
  printf("\t-m msg\tMessage to set\n");
  printf("\t-d\tDebug mode\n");
  printf("\t-p port\tSerial port being used by spsd instance\n");
  printf("\t-h\tPrint this help message\n");
}

int main(int argc, char *argv[])
{
  int ch, i;
  char spsmsg;
  char port[80], sname[80];
  dflag=0; spsmsg='2';
  strcpy(port, DEFAULT_PORT);
  while((ch = getopt(argc, argv, "m:dp:h")) != -1)
    switch(ch) {
    case 'd':
      dflag=1;
      break;
    case 'p':
      strncpy(port, optarg, 80);
      break;
    case 'm':
      if(valid_msg(optarg[0]))
	spsmsg=optarg[0];
      break;
    case 'h':
    default:
      usage(argv[0]);
      return 0;
    }
  argc -= optind;
  argv += optind;
  i=strlen(port);
  while(port[--i]!='/') {
    if(i==0) { i--; break; }
  }
  i++;
  strcpy(sname, "/tmp/");
  strcat(sname, "spsd.");
  strcat(sname, port+i);

  if(dflag) printf("spsd: socket='%s' message=%c\n", sname, spsmsg);

  send_message(sname, spsmsg);

  return 1;
}
