#!/usr/bin/env php
<?php

if (is_dir(__DIR__."/../vendor"))
  require_once __DIR__."/../vendor/autoload.php";
elseif (file_exists(__DIR__."/../../../autoload.php"))
  require_once __DIR__."/../../../autoload.php";
else
  die("Could not locate composer vendor/autoload.php");

define("PHARLITE_VERSION", "0.1.x");

if (posix_isatty(STDOUT)) {
  define("FMT_ERR", "\e[31;1m");
  define("FMT_WARN", "\e[33;1m");
  define("FMT_INFO", "\e[32m");
  define("FMT_NOTICE", "\e[33m");
  define("FMT_AFTER", "\e[0m");
} else {
  define("FMT_ERR", "");
  define("FMT_WARN", "");
  define("FMT_INFO", "");
  define("FMT_AFTER", "");
  define("FMT_NOTICE", "");
}

function print_error($fmt, ...$arg) {
  fprintf(STDOUT, FMT_ERR.$fmt."ERROR: ".FMT_AFTER.PHP_EOL, ...$arg);
}

function print_warn($fmt, ...$arg) {
  fprintf(STDOUT, FMT_WARN.$fmt.FMT_AFTER.PHP_EOL, ...$arg);
}

function print_info($fmt, ...$arg) {
  fprintf(STDOUT, FMT_INFO.$fmt.FMT_AFTER.PHP_EOL, ...$arg);
}

function print_notice($fmt, ...$arg) {
  fprintf(STDOUT, FMT_NOTICE.$fmt.FMT_AFTER.PHP_EOL, ...$arg);
}

function show_app_usage() {
  printf("options:\n");
  printf("  -I,--init   Initialize a new configuration\n");
}

function parse_opts() {

  $opts = getopt(
    "ho:d:iI",
    [
      "help",
      "directory:",
      "dir:",
      "output:",
      "install",
      "init"
    ]
  );

  $parsed = [
    'install' => false,
    'init' => false
  ];

  foreach ($opts as $option=>$value) {
    switch ($option) {
      case 'h':
      case 'help':
        show_app_usage();
        return false;
      case 'd':
      case 'dir':
      case 'directory':
        $parsed['dir'] = $value;
        break;
      case 'o':
      case 'output':
        $parsed['output'] = $value;
        break;
      case 'i':
      case 'install':
        $parsed['install'] = true;
        break;
      case 'I':
      case 'init':
        $parsed['init'] = true;
    }
  }

  return $parsed;
}

$opts = parse_opts();
if (false === $opts) {
  exit(1);
}

$path = getcwd();

$builder = new PharLite\Builder($path, $opts);
if ($opts['init']) {
    $builder->initConfig();
} else {
    $builder->build();
}
