// clang-format off

/*

 *  mc | MatterLinux Configuration Manager
 *  MatterLinux 2023-2024 (https://matterlinux.xyz)

 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.

 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.

 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <https://www.gnu.org/licenses/>.

*/

// clang-format on 

#include <libintl.h>
#include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "args.h"
#include "gen.h"
#include "lock.h"
#include "log.h"
#include "paths.h"
#include "pull.h"
#include "util.h"

#define _(x) gettext(x)

typedef bool (*cmd)();
struct CmdMap {
  char *name;
  bool lock;
  cmd func;
};

struct CmdMap cmdmap[] = {
    {.name = "mc-pull", .lock = true,  .func = pull_cmd},
    {.name = "mc-gen",  .lock = false, .func = gen_cmd },
};

int main(int argc, char *argv[]) {
  setbuf(stdout, NULL);
  setlocale(LC_ALL, "");
  textdomain("mc");

  for (int i = 0; i < sizeof(cmdmap) / sizeof(struct CmdMap); i++) {
    if (strcmp(argv[0], cmdmap[i].name) != 0)
      continue;

    args_load(argc, argv);
    
    if(!paths_load()){
      error(_("Failed to access paths (%s)"), mc_dir);
      return EXIT_FAILURE;
    }

    if (cmdmap[i].lock) {
      int st = lock();
      switch (st) {
      case ALREADY_LOCKED:
        error(_("Failed to lock, mc is already running"));
        return EXIT_FAILURE;
      case LOCK_ERROR:
        error(_("Failed to lock, did you mess up your directory permissions?"));
        return EXIT_FAILURE;
      }
    }

    bool ret = cmdmap[i].func();
    unlock();

    if (!ret) {
      error(_("%s: command failed"), cmdmap[i].name);
      return EXIT_FAILURE;
    }

    success(_("%s: command successful"), cmdmap[i].name);
    return EXIT_SUCCESS;
  }

  info(_("MatterLinux Configuration Manager (%s)"), VERSION);
  info(_("Different operations are done using different commands\n"));

  printf(COLOR_BOLD "    mc-pull" COLOR_RESET ":  ");
  printf("    %s\n", _("pull down a configuration"));

  printf(COLOR_BOLD "    mc-gen" COLOR_RESET ":   ");
  printf("    %s\n\n", _("build the configuration in the current directory"));

  info(_("Licensed under GPLv3, see <https://www.gnu.org/licenses/> for more "
         "information"));
  return EXIT_SUCCESS;
}