/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
  Copyright 2013-2021 The Libfossil Authors, see LICENSES/BSD-2-Clause.txt

  SPDX-License-Identifier: BSD-2-Clause-FreeBSD
  SPDX-FileCopyrightText: 2021 The Libfossil Authors
  SPDX-ArtifactOfProjectName: Libfossil
  SPDX-FileType: Code

  Heavily indebted to the Fossil SCM project (https://fossil-scm.org).
*/

/*****************************************************************************
  This file implements a basic libfossil client which queues new files for
  addition into a fossil repo.
*/

#include "fossil-scm/fossil-cli.h" /* Fossil App mini-framework */
#include "fossil-scm/fossil-internal.h"

int main(int argc, char const * const * argv ){
  int rc = 0;
  const char * fname;
  fsl_cx * f;
  char inTrans = 0;
  fsl_db * db;

  fcli_cliflag FCliFlags[] = {
    fcli_cliflag_empty_m
  };
  fcli_help_info FCliHelp = {
  "Queues up files to be added at the next commit.",
  "file1 [...fileN]",
  NULL
  };
  fcli.cliFlags = FCliFlags;
  fcli.appHelp = &FCliHelp;

  rc = fcli_setup(argc, argv);
  if(FCLI_RC_HELP==rc) /* --help */ return 0;
  else if(rc) goto end;
  f = fcli.f;
  db = fsl_needs_checkout(f);
  if(!db) goto end;

  if(fcli_has_unused_flags(0)) goto end;
  else if(!fcli_next_arg(false)){
    rc = fcli_err_set(FSL_RC_MISUSE,"No file names provided.");
    goto end;
  }

  rc = fsl_db_transaction_begin(db);
  if(rc){
    fsl_cx_uplift_db_error(f, db);
    goto end;
  }
  inTrans = 1;

  while((fname = fcli_next_arg(1))){
    rc = fsl_checkout_file_add( f, 1, fname );
    if(!rc){
      f_out("Queued for adding: %s\n", fname);
    }
    if(rc) goto end;
  }

  if(fcli.fDryRun){
    f_out("Dry-run mode. Rolling back transaction.\n");
    fsl_db_transaction_rollback(db);
  }else{
    rc = fsl_db_transaction_end(db, 0);
  }
  inTrans = 0;

  end:
  if(inTrans){
    fsl_db_transaction_rollback(db);
  }

  return (fcli_err_report(0)||rc) ? EXIT_FAILURE : EXIT_SUCCESS;
}
