/*
 *----------------------------------------------------------------------
 *           "THE BEER-WARE LICENSE" (Revision 42):
 * <jeang3nie@HitchHiker-Linux.org> wrote this file. As long as you
 * retain this notice you can do whatever you want with this stuff. If
 * we meet some day, and you think this stuff is worth it, you can buy
 * me a beer in return.
 * ---------------------------------------------------------------------
 *            ______   _______  _          _________
 *           (  __  \ (  ___  )( (    /|( )\__   __/
 *           | (  \  )| (   ) ||  \  ( ||/    ) (
 *           | |   ) || |   | ||   \ | |      | |
 *           | |   | || |   | || (\ \) |      | |
 *           | |   ) || |   | || | \   |      | |
 *           | (__/  )| (___) || )  \  |      | |
 *           (______/ (_______)|/    )_)      )_(
 *
 *         _______  _______  _       _________ _______
 *        (  ____ )(  ___  )( \    /|\__   __/(  ____ \
 *        | (    )|| (   ) ||  \  ( |   ) (   | (    |/
 *        | (____)|| (___) ||   \ | |   | |   | |
 *        |  _____)|  ___  || (\ \) |   | |   | |
 *        | (      | (   ) || | \   |   | |   | |
 *        | )      | )   ( || )  \  |___) (___| (____|\
 *        |/       |/     \||/    \_)\_______/(_______/
 *
 */
#define _XOPEN_SOURCE

#include <ctype.h>   // isprint
#include <libgen.h>  // basename
#include <stdio.h>   // fprintf
#include <stdlib.h>  // exit
#include <unistd.h>  // getopt, link

static const char *__progname;

static void usage() { fprintf(stderr, "usage: %s target name\n", __progname); }

int main(int argc, char *argv[]) {
  int c;
  int vflag;
  __progname = basename(argv[0]);

  while ((c = getopt(argc, argv, "hv")) != -1)
    switch (c) {
    case 'h':
      usage();
      exit(0);
    case 'v':
      vflag = 1;
      break;
    case '?':
      if (isprint(optopt)) {
        usage();
        exit(1);
      }
    default:
      usage();
    }

  // require two non-option arguments
  if (argv[optind] == NULL || argv[optind + 1] == NULL) {
    fprintf(stderr, "Mandatory argument(s) missing\n");
    exit(1);
  }

  // error on three non-option arguments
  if (argv[optind + 2] != NULL) {
    fprintf(stderr, "Too many arguments\n");
    exit(1);
  }

  // do the actual link creation
  if (link(argv[optind], argv[optind + 1]) == 0) {
    // be verbose if requested
    if (vflag) {
      fprintf(stderr, "%s: '%s' -> '%s'\n", argv[0], argv[optind],
              argv[optind + 1]);
    }
    return 0;
  } else {
    perror("link");
    exit(EXIT_FAILURE);
  }
}
