/*
 *----------------------------------------------------------------------
 *           "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 _DEFAULT_SOURCE

#include <err.h>     // warn
#include <libgen.h>  // basename
#include <limits.h>  // realpath
#include <stdio.h>   // fprintf
#include <stdlib.h>  // exit, realpath
#include <unistd.h>  // getopt, access

static const char *__progname;

static void usage() {
  fprintf(stderr, "Usage: %s path\n", __progname);
  exit(EXIT_FAILURE);
}

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

  while ((c = getopt(argc, argv, "q")) != -1)
    switch (c) {
    case 'q':
      qflag = 1;
      break;
    case '?':
    default:
      usage();
    }
  if (argv[optind] == NULL)
    usage();
  char buf[PATH_MAX];
  char *path;
  if (access(argv[optind], F_OK) == -1) {
    warn("%s", argv[optind]);
    exit(EXIT_FAILURE);
  }
  if ((path = realpath(argv[optind], buf)) == NULL) {
    if (!qflag) {
      perror("realpath");
      exit(EXIT_FAILURE);
    }
  }

  printf("%s\n", path);
  exit(EXIT_SUCCESS);
}
