#include <sys/socket.h>
#include <sys/time.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <netdb.h>
#include <ctype.h>
#include "myc_str.h"
#include "instr_hosts.h"

int rexec(char **host, int port, char *user, char *passwd, char *command, int *err_file_desc);

char *secure_arg(char *cmd, int size, char *arg) {
  int i;
/* make sure that argument is a harmless identifier and no hacker code */
  for (i=0; i<size-strlen(cmd)-2; i++) {
    if (arg[i]=='\0') { /* end of arg reached */
      strcat(cmd, " ");
      strcat(cmd, arg);
      return cmd;
    }
    if (! isalnum(arg[i]) && arg[i] != '_') {
      return NULL;
    }
  }
  return NULL;
}

int main(int argc, char *argv[]) {
  int port, i, j, l, fd;
  char inst[32], cmd[256], host[256], user[64], pcod[64];
  char *hostp, *arg;
  struct tm tim;
  time_t t;
  
  struct servent s;
  
  s=*getservbyname("exec", "tcp");
  i=0;
  if (argc < 3) {
    printf("not enough arguments\n");
    return 0;
  }
  i=InstrHost(argv[1], inst, host, user, pcod, sizeof(inst), sizeof(host), sizeof(user), sizeof(pcod));
  if (i==0) {
    printf("unknown host/instrument\n");
    return -1;
  }
  str_copy(cmd, "");
  for (i=2; i<argc; i++) {
    if (0==strcmp(argv[i], "sics")) {
      if (i<argc) {
        i++; arg=argv[i];
      } else {
        arg="";
      }
      str_append(cmd, "bin/startsics");
      secure_arg(cmd, sizeof(cmd), arg);
      str_append(cmd, "\n");
    } else if (0==strcmp(argv[i], "tecs")) {
      if (i<argc) {
        i++; arg=argv[i];
      } else {
        arg="";
      }
      str_append(cmd, "/data/lnslib/bin/startecs");
      secure_arg(cmd, sizeof(cmd), arg);
      str_append(cmd, "\n");
    } else {
      printf("unknown server %s\n", argv[i]);
      return 0;
    }
  }
  printf("login to %s\n", host);
  hostp=host;
  fd=rexec(&hostp, s.s_port, user, pcod, cmd, &i);
  if (fd<0) {
    perror("rexec"); return -1;
  }
  puts(cmd);
  close(fd);
  return 0;
}
