#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>

void check_device(const char * const dev)
{
  const char * const errmsg = "ERROR: Device \"%s\" didn't match /dev/sd[a-z] /dev/sd[a-z][a-z] /dev/nvme[0-9] /dev/nvme[0-9][0-9]\n";
  if(!strncmp(dev, "/dev/sd", 7))
  {
    if(dev[7] < 'a' || dev[7] > 'z' || (dev[8] && (dev[8] < 'a' || dev[8] > 'z' || dev[9])))
    {
      fprintf(stderr, errmsg, dev);
      exit(1);
    }
  }
  else if(!strncmp(dev, "/dev/nvme", 9))
  {
    if(dev[9] < '0' || dev[9] > '9' || (dev[10] && (dev[10] < '0' || dev[10] > '9' || dev[11])))
    {
      fprintf(stderr, errmsg, dev);
      exit(1);
    }
  }
}
int main(int argc, char **argv)
{
  if(argc != 2)
  {
    fprintf(stderr, "ERROR: Must specify device for smartctl\n");
    return 1;
  }
  char *child_args[5];
  child_args[0] = strdup("/usr/sbin/smartctl");
  if(argv[1][0] == 'M')
  {
    char *buf = strdup(argv[1] + 1);
    char *device = strtok(buf, ",");
    char *id;
    if(!device || strncmp(device, "/dev/sd", 7) || !(id = strtok(NULL, ",")) )
    {
      fprintf(stderr, "ERROR: parameter for MegaRAID must be \"M/dev/sdX,X\"\n");
      return 1;
    }
    check_device(device);
    char *megaraid = (char *)malloc(12 + strlen(id));
    strcpy(megaraid, "-dmegaraid,");
    strcpy(megaraid + 11, id);
    child_args[1] = megaraid;
    child_args[2] = strdup("-a");
    child_args[3] = device;
    child_args[4] = NULL;
  }
  else
  {
    if(strncmp(argv[1], "/dev/sd", 7) && strncmp(argv[1], "/dev/nvme", 9))
    {
      fprintf(stderr, "ERROR: First parameter must specify a /dev/sd or /dev/nvme device\n");
      return 1;
    }
    check_device(argv[1]);
    child_args[1] = strdup("-a");
    child_args[2] = argv[1];
    child_args[3] = NULL;
  }
  execv(child_args[0], (char* const*)child_args);
  fprintf(stderr, "ERROR: Can't execute %s\n", child_args[0]);
  return 1;
}

