summaryrefslogtreecommitdiff
path: root/src/aardig.c
blob: 0388782301018b5e829efedc916c3a207fab7cd9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <getopt.h>
#include <pwd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include "util/versie.h"
#include "util/error.h"
#include "util/debug.h"
#include "util/map.h"

static void usage(FILE *f) {
  fprintf(f,
      "Gebruik: aardig [-n AARDIGHEID] COMMANDO...\n"
      "\n"
      "Voer COMMANDO uit met een bepaald niveau van aardigheid.\n"
      "\n"
      "  -n AARDIGHEID   Niveau van aardigheid (standaard 10)\n"
      "  -h              Toon deze hulptekst\n"
      "  -V              Toon versienummer\n");
}

// Returns pointer to argument array containing the command arguments
static char** parse_options(int argc, char **argv, int *niceness) {
  int opt;
  while ((opt = getopt(argc, argv, "n:hV")) != -1) {
    switch (opt) {
      case 'n':
        *niceness = atoi(optarg);
        break;

      case 'h':
        usage(stdout);
        exit(0);

      case 'V':
        drukkedoos_print_versie(stdout, "aardig");
        exit(0);

      case '?':
        fprintf(stderr, "aardig: Ongeldige optie: -%c\n", optopt);
        usage(stderr);
        exit(1);
    }
  }

  return argv + optind;
}

int entry_aardig(int argc, char **argv) {
  int niceness = 10;
  char **args = parse_options(argc, argv, &niceness);

  if (*args == NULL) {
      fprintf(stderr, "aardig: geen commando opgegeven\n");
      return 1;
  }

  errno = 0;
  if (nice(niceness) == -1 && errno) {
    fprintf(stderr, "aardig: kon niet aardig worden.\n");
    return 1;
  }

  execvp(args[0], args);
  fprintf(stderr, "aardig: kon proces niet starten: %s\n", strerror(errno));

  return 1;
}