#include "uptime.h"
#include "util.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int countt = 0;

static void setT(char* ar, char i)
{
  countt++;
  if (countt > 2) {
    fprintf(stderr, "mrtg-uptime:error: only two parameters at a time. It can be sys or idle.\n");
    exit(2);
  }

  if (countt == 2) ar[1] = i;
  else             ar[0] = i;
}

static void usage(int rc)
{
  fprintf(stderr, "Usage: mrtg-uptime ([-t sys|idle] [-m multiplier] [-u s|m|h|d])*2 [-c #cores]\n");
  exit(rc);
}

int main(int argc, char **argv)
{
  char* slash;
  int c;
  double sys_uptime, idle_uptime, pos1, pos2;
  int   cores = 1;
  double mult [2] = {1,1};
  double unit [2] = {1,1};
  char   typ  [2] = {'s','i'};
  int countm = 0;
  int countu = 0;

  slash = strrchr(argv[0], '/');
  if (slash) argv[0] = slash + 1;

  while ((c = getopt(argc, argv, "t:m:u:c:")) > 0) {
    switch (c) {
      case 't':
        if (strcmp(optarg, "sys") == 0) setT(typ,'s');
        else if (strcmp(optarg, "idle") == 0) setT(typ,'i');
        else {
          fprintf(stderr, "%s:error: unknown uptime type '%s'.\nThe possible uptime types are sys and idle\n", argv[0], optarg);
          usage(2);
        }
        break;
      case 'm':
        setD(&countm, argv[0], &mult[0],atof(optarg));
        break;
      case 'u': // [-u s|m|h|d]
        if      (optarg[0] == 's') setD(&countu, argv[0], &unit[0],(float)1);      // second
        else if (optarg[0] == 'm') setD(&countu, argv[0], &unit[0],(float)60);     // minute
        else if (optarg[0] == 'h') setD(&countu, argv[0], &unit[0],(float)3600);   // hour
        else if (optarg[0] == 'd') setD(&countu, argv[0], &unit[0],(float)86400);  // day
        else {
          fprintf(stderr, "%s:error: unknown unit '%s'.\nThe possible units are (s)econds, (m)inutes, (h)ours, and (d)ays'\n", argv[0], optarg);
          usage(2);
        }
        break;
      case 'c':
        cores = atof(optarg);
        break;
      default:
	usage(0);
    }
  }

  uptime(&sys_uptime, &idle_uptime);
  pos1=sys_uptime;
  pos2=idle_uptime/(float)cores;

  switch (countt) {
  case 1:
    if (typ[0] == 's') pos1=sys_uptime;
    else pos1=idle_uptime/(float)cores;
    pos2 = 0;
    break;
  case 2:
    if (typ[0] == 's') {
       pos1=sys_uptime;
    } else {
       pos1=idle_uptime/(float)cores;
    }
    if (typ[1] == 's') {
       pos2=sys_uptime;
    } else {
       pos2=idle_uptime/(float)cores;
    }
    break;
  }

  printf("%.0f\n", pos1*mult[0]/unit[0]);
  printf("%.0f\n", pos2*mult[1]/unit[1]);
  print_uptime();
  print_hostname();
  return 0;
}
