home / secrets / src / main.c

main.c



//
//  main.c
//  secrets
//
//  Created by Anders on 08/07/2020.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "secrets.h"
#include "util/stringu.h"
#include "util/require.h"

static const char* extract_arg(int argc,
                        const char * argv[],
                        int *index,
                        const char *argshort,
                        const char *arglong) {
  const char* arg = NULL;
  if (stringu_starts_with(argv[*index], argshort)) arg = argshort;
  else if (stringu_starts_with(argv[*index], arglong)) arg = arglong;
  
  if (arg == NULL) return NULL;
  
  if (strlen(argv[*index]) == strlen(arg)) {
    require(*index < argc - 1, "missing arg after %d\n");
    return argv[++*index];
  }
  else {
    return argv[*index] + strlen(arg);
  }
}

static void print_usage(const char* name) {
  printf("usage: %s (-s file | --store file) [-i file | --input file] [-h | --help]\n", name);
  printf("  (-s | --store file): file to read/store secrets.\n");
  printf("  [-i | --input file]: store secret from a file (optional).\n");
  printf("  [-o | --output_secret]: output secret by key (optional).\n");
  printf("  [-h | --help]: show usage.\n");
}

int main(int argc, const char * argv[]) {
  const char* store_file = NULL;
  const char* input_file = NULL;
  const char* output_key = NULL;
  bool help = false;
  
  for (int i = 1; i < argc; i++) {
    if (store_file == NULL) store_file = extract_arg(argc, argv, &i, "-s", "--store_file");
    if (input_file == NULL) input_file = extract_arg(argc, argv, &i, "-i", "--input_file");
    if (output_key == NULL) output_key = extract_arg(argc, argv, &i, "-o", "--output_secret");
    help = stringu_equals("-h", argv[i]) || stringu_equals("--help", argv[i]);
  }
  
  if (help) {
    print_usage(argv[0]);
  }
  else {
    require(store_file != NULL, "missing arg [-s | --store_file] (see %s -h)\n", argv[0]);
    if (output_key != NULL) {
      secrets_output(store_file, output_key);
    }
    else {
      secrets_run(store_file, input_file);
    }
  }
  
  return EXIT_SUCCESS;
}