/* -*- 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 is for testing the ability to "remove" files from a checkout.
*/

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

static int fsl_ckout_unmanage_f_my(const char *zFilename, void *state){
  f_out("REMOVED    %s\n", zFilename);
  ++*((unsigned int*)state);
  return 0;
}

int main(int argc, char const * const * argv ){
  int rc = 0;
  fsl_cx * f;
  bool inTrans = false;
  fsl_db * db;
  fsl_id_bag idBag = fsl_id_bag_empty;
  bool fDryRun = false;
  fcli_cliflag FCliFlags[] = {
    FCLI_FLAG_BOOL("n","dry-run", &fDryRun,"Dry-run mode."),
    fcli_cliflag_empty_m
  };
  fcli_help_info FCliHelp = {
  "Queues up files to be removed at the next commit.",
  "file [...file]", NULL
  };
  fcli.cliFlags = FCliFlags;
  fcli.appHelp = &FCliHelp;
  rc = fcli_setup(argc, argv);
  if(rc) goto end;
  f = fcli_cx();
  db = fsl_cx_db_ckout(f);
  if(!db){
    rc = fsl_cx_err_set(f, FSL_RC_NOT_A_CKOUT,
                        "This app requires a checkout 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 = true;

  rc = fsl_vfile_changes_scan(f, 0, 0);
  if(rc) goto end;
  rc = fcli_args_to_vfile_ids(&idBag, 0, true, false);
  if(rc) goto end;
  unsigned int changes = 0;
  fsl_ckout_unmanage_opt ropt = fsl_ckout_unmanage_opt_empty;
  ropt.scanForChanges = false;
  ropt.vfileIds = &idBag;
  ropt.relativeToCwd = true;
  ropt.callback = fsl_ckout_unmanage_f_my;
  ropt.callbackState = &changes;
  rc = fsl_ckout_unmanage(f, &ropt);
  if(rc) goto end;
  f_out("Total number of files rm'd: %u\n", changes);

  if(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:
  fsl_id_bag_clear(&idBag);
  if(inTrans){
    fsl_db_transaction_rollback(db);
  }
  return fcli_end_of_main(rc);
}
