/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
/* vim: set ts=2 et sw=2 tw=80: */
/*
   Copyright (c) 2013 D. Richard Hipp
  
   This program is free software; you can redistribute it and/or
   modify it under the terms of the Simplified BSD License (also
   known as the "2-Clause License" or "FreeBSD License".)
  
   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.
  
   Author contact information:
     drh@hwaci.com
     http://www.hwaci.com/drh/
  
  *****************************************************************************
   This file implements a basic artifact tagging [test] app using the libfossil
   API.
*/

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

static void fapp_local_help(){
  printf("Usage:\n\t%s [options] file [...files]\n\n", fcli.appName);

  puts("Queues up files to be added at the next commit. Options:\n");
  puts("\t--dry-run|-n runs the operation in a transaction and then rolls it back.\n");
}


int main(int argc, char * const * argv ){
  int rc = 0;
  char * fname;
  fsl_cx * f;
  char inTrans = 0;
  fsl_db * db;
  char dryRun;
  fsl_id_t ckoutId = 0;
  fcli.appHelp = fapp_local_help;
  rc = fcli_setup(argc, argv);
  if(FSL_RC_BREAK==rc) /* --help */ return 0;
  else if(rc) goto end;
  f = fcli.f;
  db = fsl_cx_db_checkout(f);
  if(!db){
    rc = fsl_cx_err_set(f, FSL_RC_NOT_A_CHECKOUT,
                        "This app requires a checkout db.");
    goto end;
  }

  dryRun = fcli.fDryRun || fcli_flag("n",NULL);

  if(fcli_has_unused_flags(0)) goto end;

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

  fsl_checkout_version_info(f, &ckoutId, NULL);

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

  if(dryRun){
    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;
}
