/* -*- 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 houses most of the context-related APIs.
*/
#include "fossil-scm/fossil-internal.h"
#include <assert.h>
#include "fossil-ext_regexp.h"
#include "fossil-vtbl_fossil_settings.h"
#include "sqlite3.h"

#if defined(_WIN32)
# include <windows.h>
# define F_OK 0
# define W_OK 2
#else
# include <unistd.h> /* F_OK */
#endif

#include <stdlib.h>

/* Only for debugging */
#include <stdio.h>
#define MARKER(pfexp)                                               \
  do{ printf("MARKER: %s:%d:%s():\t",__FILE__,__LINE__,__func__);   \
    printf pfexp;                                                   \
  } while(0)


static volatile long sg_autoregctr = 0;


#ifdef WIN32
#define ATOMIC_INCREMENT(a) InterlockedIncrement ( &a )
#define ATOMIC_DECREMENT(a) InterlockedDecrement ( &a )
#elif defined(__GNUC__)
#define ATOMIC_INCREMENT(a) __sync_add_and_fetch ( &a, 1 )
#define ATOMIC_DECREMENT(a) __sync_sub_and_fetch ( &a, 1 )
#else
/*OSSpin*() on macs*/
/*hail mary*/
#define ATOMIC_INCREMENT(a) (++(a))
#define ATOMIC_DECREMENT(a) (--(a))
#endif



int fsl_cx_init( fsl_cx ** tgt, fsl_cx_init_opt const * param ){
  static fsl_cx_init_opt paramDefaults = fsl_cx_init_opt_default_m;
  int rc = 0;
  fsl_cx * f;
  if(!tgt) return FSL_RC_MISUSE;
  else if(!param){
    if(!paramDefaults.output.state.state){
      paramDefaults.output.state.state = stdout;
    }
    param = &paramDefaults;
  }
  if(*tgt){
    void const * allocStamp = (*tgt)->allocStamp;
    fsl_cx_reset(*tgt, 1) /* just to be safe */;
    f = *tgt;
    *f = fsl_cx_empty;
    f->allocStamp = allocStamp;
  }else{
    f = fsl_cx_malloc();
    if(!f) return FSL_RC_OOM;

    *tgt = f;
  }
  f->output = param->output;
  f->cxConfig = param->config;
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  sqlite3_initialize(); /*the SQLITE_MUTEX_STATIC_MASTER will not cause autoinit of sqlite for some reason*/
  sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
#endif
    if ( 1 == ++sg_autoregctr )
    {
      /*register our statically linked extensions to be auto-init'ed at the appropriate time*/
      sqlite3_auto_extension((void(*)(void))(sqlite3_vtbl_fossilsettings_init));  /*our settings vtables*/
      sqlite3_auto_extension((void(*)(void))(sqlite3_regexp_init));     /*sqlite regexp extension*/
      atexit(sqlite3_reset_auto_extension)
        /* Clean up pseudo-leak valgrind complains about:
           https://www.sqlite.org/c3ref/auto_extension.html */;
    }
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
#endif
  f->dbMem.f = f /* so that dbMem gets fsl_xxx() SQL funcs installed. */;
  rc = fsl_db_open( &f->dbMem, "", 0 );
  if(!rc){
    /* Attempt to ensure that the TEMP tables/indexes use FILE storage. */
    rc = fsl_db_exec(&f->dbMem, "PRAGMA temp_store=FILE;");
  }
  if(rc){
    if(f->dbMem.error.code){
      fsl_cx_uplift_db_error(f, &f->dbMem);
    }
  }else{
    f->dbMain = &f->dbMem;
    f->dbMem.role = FSL_DB_ROLE_MAIN;
  }

  return rc;
}
    
void fsl_cx_reset(fsl_cx * f, char closeDatabases){
  if(!f) return;
  fsl_checkin_discard(f);
#define SFREE(X) fsl_free(X); X = NULL
  if(closeDatabases){
    fsl_cx_close_dbs(f);
    /*
      Reminder: f->dbMem is NOT closed here: it's an internal detail,
      not public state. We could arguably close and reopen it here,
      but then we introduce a potenital error case (OOM) where we
      currently have none (thus the void return).
    */
    SFREE(f->ckout.dir);
    f->ckout.dirLen = 0;
    /* assert(NULL==f->dbMain); */
    assert(!f->repo.db.dbh);
    assert(!f->ckout.db.dbh);
    assert(!f->config.db.dbh);
    assert(!f->repo.db.filename);
    assert(!f->ckout.db.filename);
    assert(!f->config.db.filename);
  }
  SFREE(f->repo.user);
  SFREE(f->ckout.uuid);
  SFREE(f->cache.projectCode);
#undef SFREE
  fsl_error_clear(&f->error);
  fsl_card_J_list_free(&f->ticket.customFields, 1);
  fsl_buffer_clear(&f->scratch);
  fsl_buffer_clear(&f->fsScratch);
  fsl_buffer_clear(&f->fileContent);
  fsl_acache_clear(&f->cache.arty);
  fsl_id_bag_clear(&f->cache.leafCheck);
  fsl_id_bag_clear(&f->cache.toVerify);
  fsl_cx_clear_mf_seen(f);
#define SLIST(L) fsl_list_visit_free(L, 1)
#define GLOBL(X) SLIST(&f->cache.globs.X)
  GLOBL(ignore);
  GLOBL(binary);
  GLOBL(crnl);
#undef GLOBL
#undef SLIST
  while( f->cache.mf.head ){
    fsl_deck * next = f->cache.mf.head->next;
    f->cache.mf.head->next = NULL;
    fsl_deck_finalize(f->cache.mf.head);
    f->cache.mf.head = next;
  }
  f->cache = fsl_cx_empty.cache;
}

void fsl_cx_clear_mf_seen(fsl_cx * f){
  fsl_id_bag_clear(&f->cache.mfSeen);
}

void fsl_cx_finalize( fsl_cx * f ){
  void const * allocStamp = f ? f->allocStamp : NULL;
  if(!f) return;

  if(f->xlinkers.list){
#if 0
    /* Potential TODO: add client-specified finalizer for xlink
       callback state, using a fsl_state to replace the current
       (void*) for x->state. Seems like overkill for the time being.
     */
    fsl_size_t i;
    for( i = 0; i < f->xlinkers.used; ++i ){
      fsl_xlinker * x = f->xlinkers.list + i;
      if(x->state.finalize.f){
        x->state.finalize.f(x->state.finalize.state, x->state.state);
      }
    }
#endif    
    fsl_free(f->xlinkers.list);
    f->xlinkers = fsl_xlinker_list_empty;
  }

  if(f->clientState.finalize.f){
    f->clientState.finalize.f( f->clientState.finalize.state,
                               f->clientState.state );
  }
  f->clientState = fsl_state_empty;
  if(f->output.state.finalize.f){
    f->output.state.finalize.f( f->output.state.finalize.state,
                                f->output.state.state );
  }
  f->output = fsl_outputer_empty;
  fsl_cx_reset(f, 1);
  fsl_db_close(&f->dbMem);
  *f = fsl_cx_empty;
  if(&fsl_cx_empty == allocStamp){
    fsl_free(f);
  }else{
    f->allocStamp = allocStamp;
  }

  /* clean up the auto extension; not strictly necessary, but pleases debug malloc's */
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
#endif
  if ( 0 == --sg_autoregctr )
  {
    /*register our statically linked extensions to be auto-init'ed at the appropriate time*/
    sqlite3_cancel_auto_extension((void(*)(void))(sqlite3_vtbl_fossilsettings_init));  /*our settings vtables*/
    sqlite3_cancel_auto_extension((void(*)(void))(sqlite3_regexp_init));     /*sqlite regexp extension*/
  }
  assert(sg_autoregctr>=0);
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
#endif
}

void fsl_cx_err_reset(fsl_cx * f){
  if(f){
    fsl_error_reset(&f->error);
    fsl_db_err_reset(&f->dbMem);
    fsl_db_err_reset(&f->repo.db);
    fsl_db_err_reset(&f->config.db);
    fsl_db_err_reset(&f->ckout.db);
  }
}

int fsl_cx_err_set_e( fsl_cx * f, fsl_error * err ){
  if(!f) return FSL_RC_MISUSE;
  else if(!err){
    return fsl_cx_err_set(f, 0, NULL);
  }else{
    fsl_error_move(err, &f->error);
    fsl_error_clear(err);
    return f->error.code;
  }
}

int fsl_cx_err_setv( fsl_cx * f, int code, char const * fmt,
                     va_list args ){
  return f
    ? fsl_error_setv( &f->error, code, fmt, args )
    : FSL_RC_MISUSE;
}

int fsl_cx_err_set( fsl_cx * f, int code, char const * fmt,
                    ... ){
  if(!f) return FSL_RC_MISUSE;
  else{
    int rc;
    va_list args;
    va_start(args,fmt);
    rc = fsl_error_setv( &f->error, code, fmt, args );
    va_end(args);
    return rc;
  }
}

int fsl_cx_err_get( fsl_cx * f, char const ** str, fsl_size_t * len ){
  return f
    ? fsl_error_get( &f->error, str, len )
    : FSL_RC_MISUSE;
}

fsl_id_t fsl_cx_last_insert_id(fsl_cx * f){
  return (f && f->dbMain && f->dbMain->dbh)
    ? fsl_db_last_insert_id(f->dbMain)
    : -1;
}

fsl_cx * fsl_cx_malloc(){
  fsl_cx * rc = (fsl_cx *)fsl_malloc(sizeof(fsl_cx));
  if(rc) {
    *rc = fsl_cx_empty;
    rc->allocStamp = &fsl_cx_empty;
  }
  return rc;
}

int fsl_cx_err_report( fsl_cx * f, char addNewline ){
  if(!f) return FSL_RC_MISUSE;
  else if(f->error.code){
    char const * msg = f->error.msg.used
      ? (char const *)f->error.msg.mem
      : fsl_rc_cstr(f->error.code)
      ;
    return fsl_outputf(f, "Error #%d: %s%s",
                       f->error.code, msg,
                       addNewline ? "\n" : "");
  }
  else return 0;
}

int fsl_cx_uplift_db_error( fsl_cx * f, fsl_db * db ){
  assert(f);
  if(!f) return FSL_RC_MISUSE;
  if(!db){
    db = f->dbMain;
    assert(db && "misuse: no DB handle to uplift error from!");
    if(!db) return FSL_RC_MISUSE;
  }
  fsl_error_move( &db->error, &f->error );
  return f->error.code;
}


fsl_db * fsl_cx_db_config( fsl_cx * f ){
  if(!f) return NULL;
  else if(f->config.db.dbh) return &f->config.db;
  else if(f->dbMain && (FSL_DB_ROLE_CONFIG & f->dbMain->role)) return f->dbMain;
  else return NULL;
}

fsl_db * fsl_cx_db_repo( fsl_cx * f ){
  if(!f) return NULL;
  else if(f->repo.db.dbh) return &f->repo.db;
  else if(f->dbMain && (FSL_DB_ROLE_REPO & f->dbMain->role)) return f->dbMain;
  else return NULL;
}

fsl_db * fsl_needs_repo(fsl_cx * f){
  fsl_db * db = f ? fsl_cx_db_repo(f) : NULL;
  if(f && !db) fsl_cx_err_set(f, FSL_RC_NOT_A_REPO,
                              "Fossil has no opened repository db.");
  return db;
}

fsl_db * fsl_needs_checkout(fsl_cx * f){
  fsl_db * db = f ? fsl_cx_db_checkout(f) : NULL;
  if(f && !db) fsl_cx_err_set(f, FSL_RC_NOT_A_CHECKOUT,
                              "Fossil has no opened checkout db.");
  return db;
}

fsl_db * fsl_cx_db_checkout( fsl_cx * f ){
  if(!f) return NULL;
  else if(f->ckout.db.dbh) return &f->ckout.db;
  else if(f->dbMain && (FSL_DB_ROLE_CHECKOUT & f->dbMain->role)) return f->dbMain;
  else return NULL;
}

fsl_db * fsl_cx_db_versioned( fsl_cx * f ){
  /*the 'versioned settings' is a virtual table strapped onto the checkout db*/
  return fsl_cx_db_checkout ( f );
}

fsl_db * fsl_cx_db_metadata( fsl_cx * f ){
  /*the 'settings metadata' is a virtual table strapped onto the main db*/
  return fsl_cx_db ( f );
}

fsl_db * fsl_cx_db( fsl_cx * f ){
  return f ? f->dbMain : NULL;
}




/**
    Returns one of f->db{Config,Repo,Ckout,Mem}
    or NULL.
 */
static fsl_db * fsl_cx_db_for_role(fsl_cx * f, fsl_db_role_t r){
  switch(r){
    case FSL_DB_ROLE_CONFIG:
      return &f->config.db;
    case FSL_DB_ROLE_REPO:
      return &f->repo.db;
    case FSL_DB_ROLE_CHECKOUT:
      return &f->ckout.db;
    case FSL_DB_ROLE_MAIN:
      return &f->dbMem;
    case FSL_DB_ROLE_NONE:
    default:
      return NULL;
  }
}

/**
    Deattaches the given db role from f->dbMain and removes the role
    from f->dbMain->role. 
 */
static int fsl_cx_detach_role(fsl_cx * f, fsl_db_role_t r){
  if(!f || !f->dbMain) return FSL_RC_MISUSE;
  else if(!(r & f->dbMain->role)){
    assert(!"Misuse: cannot detach unattached role.");
    return FSL_RC_NOT_FOUND;
  }
  else{
    fsl_db * db = fsl_cx_db_for_role(f,r);
    int rc;
    if(!db) return FSL_RC_RANGE;
    assert(f->dbMain != db);
    f->dbMain->role &= ~r;
    rc = fsl_db_detach( f->dbMain, fsl_db_role_label(r) );
    fsl_free(db->filename);
    fsl_free(db->name);
    db->filename = NULL;
    db->name = NULL;
    return rc;
  }
}


static int fsl_cx_attach_role(fsl_cx * f, const char *zDbName, fsl_db_role_t r){
  char const * label = fsl_db_role_label(r);
  fsl_db * db = fsl_cx_db_for_role(f, r);
  char ** nameDest = NULL;
  int rc;
  if(!f->dbMain){
    assert(!"Misuse: f->dbMain has not been set: cannot attach role.");
    return FSL_RC_MISUSE;
  }
  else if(r & f->dbMain->role){
    assert(!"Misuse: role is already attached.");
    return FSL_RC_ACCESS;
  }
  assert(db);
  assert(label);
  assert(f->dbMain != db);
  assert(!db->filename);
  assert(!db->name);
  nameDest = &db->filename;
  switch(r){
    case FSL_DB_ROLE_CONFIG:
    case FSL_DB_ROLE_REPO:
    case FSL_DB_ROLE_CHECKOUT:
      break;
    case FSL_DB_ROLE_MAIN:
    case FSL_DB_ROLE_NONE:
    default:
      assert(!"cannot happen/not legal");
      return FSL_RC_RANGE;
  }
  *nameDest = fsl_strdup(zDbName);
  db->name = *nameDest ? fsl_strdup(label) : NULL;
  if(!db->name){
    rc = FSL_RC_OOM;
    /* Design note: we do the strdup() before the ATTACH because if
       the attach succeeds and strdup fails, detaching the db will
       almost certainly fail because it must allocate for its prepared
       statement and other internals. We would end up having to leave
       the db attached and returning a failure, which could lead to a
       memory leak (or worse) downstream.
    */
  }else{
    rc = fsl_db_attach(f->dbMain, zDbName, label);
    if(rc){
      fsl_cx_uplift_db_error(f, f->dbMain);
    }else{
      f->dbMain->role |= r;
    }
  }
  return rc;
}


/*
   Analog to v1's db_open_or_attach().
  
   This function is still very much up for reconsideration. i'm not
   terribly happy with the "db roles" here - i'd prefer to have them
   each in their own struct, but understand that the roles may play a
   part in query generation, so i haven't yet ruled them out. On
   20140724 we got a fix which allows us to publish concrete names for
   all dbs, regardless of which one is the "main", so much of the
   reason for that concern has been alleviated. In late October, 2014,
   Dave figured out that multi-attach leads to locking problems, so
   the innards are being rewritten to use a :memory: db as the
   permanent "main", and attaching the others.



   Opens or attaches the given db file. zDbName is the
   file name of the DB. role is the role of that db
   in the framework (that determines its db name in SQL).
  
   The first time this is called, f->dbMain is set to point
   to fsl_cx_db_for_role(f, role).
  
   If f->dbMain is already set then the db is attached using a
   role-dependent name and role is added to f->dbMain->role's bitmask.
  
   If f->dbMain is not open then it is opened here and its role is set
   to the given role. It is _also_ ATTACHED using its role name. This
   allows us to publish the names of all Fossil-managed db handles
   regardless of which one is "main". e.g. if repo is opened first, it
   is addressable from SQL as both "main" or "repo".
  
   The given db zDbName is the name of a database file.  If f->dbMain
   is not opened then that db is assigned to the given db file,
   otherwise attach attach zDbName using the name zLabel.
  
   If pWasAttached is not NULL then it is set to a true value if the
   db gets attached, else a false value. It is only modified on success.
  
   It is an error to open the same db role more than once, and trying
   to do so results in a FSL_RC_ACCESS error (f's error state is
   updated).
*/
static int fsl_cx_db_main_open_or_attach( fsl_cx * f,
                                          const char *zDbName,
                                          /* const char *zLabel, */
                                          fsl_db_role_t role,
                                          int *pWasAttached){
  int rc;
  int wasAttached = 0;
  fsl_db * db;
  assert(f);
  assert(zDbName && *zDbName);
  assert((FSL_DB_ROLE_CONFIG==role)
         || (FSL_DB_ROLE_CHECKOUT==role)
         || (FSL_DB_ROLE_REPO==role));
  if(!f || !zDbName) return FSL_RC_MISUSE;
  else if((FSL_DB_ROLE_NONE==role) || !*zDbName) return FSL_RC_RANGE;
  switch(role){
    case FSL_DB_ROLE_REPO:
    case FSL_DB_ROLE_CHECKOUT:
    case FSL_DB_ROLE_CONFIG:
      db = fsl_cx_db_for_role(f, role);
      break;
    default:
      assert(!"not possible");
      db = NULL;
      /* We'll fall through and segfault in a moment... */
  }
  assert(db);
  try_again:
  if(!f->dbMain) {
    assert(!"Not possible since moving to a :memory: main db.");
    /* This is the first db. It is now our main db. */
    assert( FSL_DB_ROLE_NONE==db->role );
    assert( NULL==db->dbh );
    assert( role == FSL_DB_ROLE_CONFIG
            || role == FSL_DB_ROLE_REPO 
            || role == FSL_DB_ROLE_CHECKOUT );
    f->dbMain = db;
    db->f = f;
    rc = fsl_db_open( db, zDbName, FSL_OPEN_F_RW );
    if(!rc){
      db->role = role;
      assert(!db->name);
#if 0
      db->name = fsl_strdup( fsl_db_role_label(FSL_DB_ROLE_MAIN) );
      if(!db->name) rc = FSL_RC_OOM;
#else
      /* Many thanks to Simon Slavin, native resident of the sqlite3
         mailing list, for this... we apply the db's "real" name via
         an ATTACH, meaning that all the client-side kludgery to get the
         proper DB name is now obsolete.
      */
      rc = fsl_db_attach( db, zDbName, fsl_db_role_label(role) );
      if(!rc){
        db->name = fsl_strdup( fsl_db_role_label(role) );
        if(!db->name) rc = FSL_RC_OOM;
      }
#endif
    }
    /* MARKER(("db->role=%d\n",db->role)); */
    /* g.db = fsl_db_open(zDbName); */
    /* g.zMainDbType = zLabel; */
    /* f->mainDbType = zLabel; */
    /* f->dbMain.role = FSL_DB_ROLE_MAIN; */
  }else{
    /* Main db has already been opened. Attach this one to it... */
    assert( (int)FSL_DB_ROLE_NONE!=f->dbMain->role );
    assert( f == f->dbMain->f );
    if(NULL == f->dbMain->dbh){
      /* It was closed in the meantime. Re-assign dbMain... */
      MARKER(("Untested: re-assigning f->dbMain after it has been closed.\n"));
      assert(!"Broken by addition of f->dbMem.");
      f->dbMain = NULL;
      goto try_again;
    }
    if((int)role == db->role){
      return fsl_cx_err_set(f, FSL_RC_ACCESS,
                            "Cannot open/attach db role "
                            "#%d (%s) more than once.",
                            (int)role, fsl_db_role_label(role));
    }
    rc = fsl_cx_attach_role(f, zDbName, role);
    wasAttached = 1;
  }
  if(!rc){
    if(pWasAttached) *pWasAttached = wasAttached;
  }else{
    if(db->error.code){
      fsl_cx_uplift_db_error(f, db);
    }
    if(db==f->dbMain) f->dbMain = NULL;
    fsl_db_close(db);
  }
  return rc;
}


int fsl_config_close( fsl_cx * f ){
  if(!f) return FSL_RC_MISUSE;
  else{
    int rc;
    fsl_db * db = &f->config.db;
    if(db->dbh){
      /* Config is our main db. Close them all */
      assert(!"Not possible since f->dbMem added.");
      assert(f->dbMain==db);
      fsl_checkout_close(f);
      fsl_repo_close(f);
      rc = fsl_db_close(db);
      f->dbMain = NULL;
    }else if(f->dbMain && (FSL_DB_ROLE_CONFIG & f->dbMain->role)){
      /* Config db is ATTACHed. */
      assert(f->dbMain!=db);
      rc = fsl_cx_detach_role(f, FSL_DB_ROLE_CONFIG);
    }
    else rc = FSL_RC_NOT_FOUND;
    assert(!db->dbh);
    fsl_db_clear_strings(db, 1);
    return rc;
  }
}

int fsl_repo_close( fsl_cx * f ){
  if(!f) return FSL_RC_MISUSE;
  else{
    int rc;
    fsl_db * db = &f->repo.db;
    if(db->dbh){
      /* Repo is our main db. Close them all */
      assert(!"Not possible since f->dbMem added.");
      assert(f->dbMain==db);
      fsl_config_close(f);
      fsl_checkout_close(f);
      rc = fsl_db_close(db);
      f->dbMain = NULL;
    }else if(f->dbMain && (FSL_DB_ROLE_REPO & f->dbMain->role)){
      /* Repo db is ATTACHed. */
      assert(f->dbMain!=db);
      rc = fsl_cx_detach_role(f, FSL_DB_ROLE_REPO);
    }
    else rc = FSL_RC_NOT_FOUND;
    assert(!db->dbh);
    fsl_db_clear_strings(db, 1);
    return rc;
  }
}

int fsl_checkout_close( fsl_cx * f ){
  if(!f) return FSL_RC_MISUSE;
  else{
    int rc;
    fsl_db * db = &f->ckout.db;
#if 0
    fsl_repo_close(f)
        /*
          Ignore error - it might not be opened.  Close it first
          because it was (if things went normally) attached to
          f->ckout.db resp. HOWEVER: we have a bug-in-waiting here,
          potentially. If repo becomes the main db for an attached
          checkout (which isn't current possibly because opening a
          checkout closes/(re)opens the repo) then we stomp on our db
          handle here. Hypothetically.

          If the repo is dbMain:

          a) we cannot have a checkout because fsl_repo_open()
          fails if a repo is already opened.

          b) fsl_repo_close() will clear f->dbMain,
          leaving the code below to return FSL_RC_NOT_FOUND,
          which would be misleading.

          But that's all hypothetical - best we make it impossible
          for the public API to have a checkout without a repo
          or a repo/checkout mismatch.
        */
        ;
#endif
    if(db->dbh){
      /* checkout is our main db. Close them all. */
      assert(!"Not possible since f->dbMem added.");
      assert(!f->repo.db.dbh);
      assert(f->dbMain==db);
      fsl_repo_close(f);
      fsl_config_close(f);
      rc = fsl_db_close(db);
      f->dbMain = NULL;
    }
    else if(f->dbMain && (FSL_DB_ROLE_CHECKOUT & f->dbMain->role)){
      /* Checkout db is ATTACHed. */
      assert(f->dbMain!=db);
      rc = fsl_cx_detach_role(f, FSL_DB_ROLE_CHECKOUT);
      fsl_repo_close(f) /*
                          Because the repo is implicitly opened, we
                          "should" implicitly close it. This is
                          debatable but "probably almost always"
                          desired. i can't currently envisage a
                          reasonable use-case which requires closing
                          the checkout but keeping the repo opened.
                          The repo can always be re-opened by itself.
                        */;
    }
    else{
      rc = FSL_RC_NOT_FOUND;
    }
    fsl_free(f->ckout.uuid);
    f->ckout.uuid = NULL;
    f->ckout.rid = 0;
    assert(!db->dbh);
    fsl_db_clear_strings(db, 1);
    return rc;
  }
}

/**
   If zDbName is a valid checkout database file, open it and return 0.
   If it is not a valid local database file, return a non-0 code.
*/
static int fsl_cx_checkout_open_db(fsl_cx * f, const char *zDbName){
  fsl_size_t lsize;
  /* char *zVFileDef; */
  int rc;
  lsize = fsl_file_size(zDbName);
  if( (fsl_size_t)-1 == lsize  ){
    return FSL_RC_NOT_FOUND /* FSL_RC_ACCESS? */;
  }
  if( lsize%1024!=0 || lsize<4096 ) return FSL_RC_RANGE;
  rc = fsl_cx_db_main_open_or_attach(f, zDbName,
                                     FSL_DB_ROLE_CHECKOUT,
                                     NULL);
  if(rc){
    fsl_cx_uplift_db_error(f, NULL);
  }
  return rc;
#if 0
  /* Historical bits: no longer needed(?). */

  zVFileDef = fsl_db_text(0, "SELECT sql FROM %s.sqlite_master"
                          " WHERE name=='vfile'",
                          fsl_cx_db_name("localdb")); /* ==> "ckout" */
  if( zVFileDef==0 ) return 0;

  /* If the "isexe" column is missing from the vfile table, then
     add it now.   This code added on 2010-03-06.  After all users have
     upgraded, this code can be safely deleted.
  */
  if( !fsl_str_glob("* isexe *", zVFileDef) ){
    fsl_db_multi_exec("ALTER TABLE vfile ADD COLUMN isexe BOOLEAN DEFAULT 0");
  }

  /* If "islink"/"isLink" columns are missing from tables, then
     add them now.   This code added on 2011-01-17 and 2011-08-27.
     After all users have upgraded, this code can be safely deleted.
  */
  if( !fsl_str_glob("* islink *", zVFileDef) ){
    db_multi_exec("ALTER TABLE vfile ADD COLUMN islink BOOLEAN DEFAULT 0");
    if( db_local_table_exists_but_lacks_column("stashfile", "isLink") ){
      db_multi_exec("ALTER TABLE stashfile ADD COLUMN isLink BOOL DEFAULT 0");
    }
    if( db_local_table_exists_but_lacks_column("undo", "isLink") ){
      db_multi_exec("ALTER TABLE undo ADD COLUMN isLink BOOLEAN DEFAULT 0");
    }
    if( db_local_table_exists_but_lacks_column("undo_vfile", "islink") ){
      db_multi_exec("ALTER TABLE undo_vfile ADD COLUMN islink BOOL DEFAULT 0");
    }
  }
#endif
  return 0;
}


int fsl_cx_prepare( fsl_cx *f, fsl_stmt * tgt, char const * sql,
                      ... ){
  if(!f || !f->dbMain) return FSL_RC_MISUSE;
  else{
    int rc;
    va_list args;
    va_start(args,sql);
    rc = fsl_db_preparev( f->dbMain, tgt, sql, args );
    va_end(args);
    return rc;
  }
}

int fsl_cx_preparev( fsl_cx *f, fsl_stmt * tgt, char const * sql,
                       va_list args ){
  return (f && f->dbMain && tgt)
    ? fsl_db_preparev(f->dbMain, tgt, sql, args)
    : FSL_RC_MISUSE;
}

/**
    Passes the fsl_schema_config() SQL code through a new/truncated
    file named dbName. If the file exists before this call, it is
    unlink()ed and fails if that operation fails.
 */
static int fsl_config_file_reset(fsl_cx * f, char const * dbName){
  fsl_db DB = fsl_db_empty;
  fsl_db * db = &DB;
  int rc = 0;
  if((fsl_size_t)-1 != fsl_file_size(dbName)){
    rc = fsl_file_unlink(dbName);
    if(rc){
      return fsl_cx_err_set(f, rc,
                            "Error %s while removing old config file (%s)",
                            fsl_rc_cstr(rc), dbName);
    }
  }
  rc = fsl_db_open(db, dbName, FSL_OPEN_F_RWC);
  if(!rc) rc = fsl_db_exec_multi(db, "%s", fsl_schema_config());
  if(rc && db->error.code){
    rc = fsl_cx_uplift_db_error(f, db);
  }
  fsl_db_close(db);
  return rc;
}

int fsl_config_open( fsl_cx * f, char const * openDbName ){
  int rc = 0;
  char const *zDbName = NULL;
  fsl_buffer dbPath = fsl_buffer_empty;
  char useAttach = 0; /* TODO? Move this into a parameter? Do we need the v1 behaviour? */
  if(!f) return FSL_RC_MISUSE;
  else if(f->config.db.dbh){
    fsl_config_close(f);
  }

  if(openDbName && *openDbName){
    zDbName = openDbName;
  }else{
    rc = fsl_find_home_dir( &dbPath, 1 );
    if(!rc){
      char const * dbName =
#if defined(_WIN32) || defined(__CYGWIN__)
        /* . filenames give some window systems problems and many apps problems */
        "_fossil"
#else
        ".fossil"
#endif
        ;
      rc = fsl_buffer_appendf(&dbPath, "/%s", dbName);
      if(rc){
        rc = fsl_cx_err_set(f, rc, "%.*s", (int)dbPath.used, fsl_buffer_cstr(&dbPath));
        fsl_buffer_reserve(&dbPath, 0);
        return rc;
      }
    }
    assert(dbPath.used);
    zDbName = fsl_buffer_cstr(&dbPath);
  }

  {
    fsl_size_t fsize = fsl_file_size(zDbName);
    if( ((fsl_size_t)-1==fsize) || (fsize<1024*3) ){
      rc = fsl_config_file_reset(f, zDbName);
      if(rc){
        fsl_buffer_reserve(&dbPath,0);
        return rc;
      }
    }
  }

#if defined(_WIN32) || defined(__CYGWIN__)
  /* TODO: Jan made some changes in this area in fossil(1) in
     January(?) 2014, such that only the config file needs to be
     writable, not the directory. Port that in.
  */
  if( fsl_file_access(zDbName, W_OK) ){
    rc = fsl_cx_err_set(f, FSL_RC_ACCESS,
                        "Configuration database [%s] "
                        "must be writeable.", zDbName);
    fsl_buffer_reserve(&dbPath,0);
    return rc;
  }
#endif

  if( useAttach ){
    rc = fsl_cx_attach_role(f, zDbName, FSL_DB_ROLE_CONFIG);
  }else{
    rc = fsl_cx_db_main_open_or_attach(f, zDbName,
                                       FSL_DB_ROLE_CONFIG,
                                       NULL);
    /* rc = fsl_db_open(&f->config.db, zDbName, FSL_OPEN_F_RWC ); */
  }
  fsl_buffer_reserve(&dbPath,0);
  /* g.zConfigDbName = zDbName; */
  if(!rc && !f->dbMain){
    f->dbMain = &f->config.db;
  }
  return rc;
}

static void fsl_cx_username_from_repo(fsl_cx * f){
  fsl_db * dbR = fsl_cx_db_repo(f);
  char * u;
  assert(dbR);
  u = fsl_db_g_text(fsl_cx_db_repo(f), NULL,
                    "SELECT login FROM user WHERE uid=1");
  if(u){
    fsl_free(f->repo.user);
    f->repo.user = u;
  }
}

static int fsl_cx_load_glob_lists(fsl_cx * f){
  int rc;
  rc = fsl_config_globs_load(f, &f->cache.globs.ignore, "ignore-glob");
  if(!rc) rc = fsl_config_globs_load(f, &f->cache.globs.binary, "binary-glob");
  if(!rc) rc = fsl_config_globs_load(f, &f->cache.globs.crnl, "crnl-glob");
  return rc;
}

/**
   To be called after a repo or checkout/repo combination has been
   opened. This updates some internal cached info based on the
   checkout and/or repo.
*/
static int fsl_cx_after_open(fsl_cx * f){
  int rc = fsl_cx_update_checkout_uuid(f);
  if(!rc) rc = fsl_cx_load_glob_lists(f);
  return rc;
}

int fsl_repo_open( fsl_cx * f, char const * repoDbFile/* , char readOnlyCurrentlyIgnored */ ){
  if(!f || !repoDbFile || !*repoDbFile) return FSL_RC_MISUSE;
  else if(fsl_cx_db_repo(f)){
    return fsl_cx_err_set(f, FSL_RC_ACCESS,
                          "Context already has an opened repository.");
  }
  else {
    int rc;
    if(0!=fsl_file_access( repoDbFile, F_OK )){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "Repository db [%s] not found or cannot be read.",
                          repoDbFile);
    }else{
      rc = fsl_cx_db_main_open_or_attach(f, repoDbFile,
                                         FSL_DB_ROLE_REPO,
                                         NULL);
      if(!rc && !(FSL_CX_F_IS_OPENING_CKOUT & f->flags)){
        rc = fsl_cx_after_open(f);
      }
      if(!rc){
        fsl_cx_username_from_repo(f);
        f->cache.allowSymlinks =
          fsl_config_get_bool(f, FSL_CONFDB_REPO,
                              f->cache.allowSymlinks,
                              "allow-symlinks");
      }
    }
    return rc;
  }
}

/**
    Tries to open the repository which from which the current checkout
    derives.  Returns 0 on success.
*/
static int fsl_repo_open_for_checkout(fsl_cx * f){
  char * repoDb = NULL;
  int rc;
  fsl_buffer nameBuf = fsl_buffer_empty;
  fsl_db * db = fsl_cx_db_checkout(f);
  assert(f);
  assert(f->ckout.dir);
  assert(db);
  rc = fsl_db_get_text(db, &repoDb, NULL,
                       "SELECT value FROM vvar "
                       "WHERE name='repository'");
  if(rc) fsl_cx_uplift_db_error( f, db );
  else if(repoDb){
    if(!fsl_is_absolute_path(repoDb)){
      /* Make it relative to the checkout db dir */
      rc = fsl_buffer_appendf(&nameBuf, "%s/%s", f->ckout.dir, repoDb);
      fsl_free(repoDb);
      if(rc) {
        fsl_buffer_clear(&nameBuf);
        return rc;
      }
      repoDb = (char*)nameBuf.mem /* transfer ownership */;
      nameBuf = fsl_buffer_empty;
    }
    rc = fsl_file_canonical_name(repoDb, &nameBuf, 0);
    fsl_free(repoDb);
    if(!rc){
      repoDb = fsl_buffer_str(&nameBuf);
      assert(repoDb);
      rc = fsl_repo_open(f, repoDb);
    }
    fsl_buffer_reserve(&nameBuf, 0);
  }else{
    /* This can only happen if we are not using a proper
       checkout db or someone has removed the repo link.
    */
    rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                        "Could not determine this checkout's "
                        "repository db file.");
  }
  return rc;
}

int fsl_cx_update_checkout_uuid( fsl_cx *f ){
  fsl_id_t rid = 0;
  int rc = 0;
  fsl_db * dbC = fsl_cx_db_checkout(f);
  fsl_db * dbR = dbC ? fsl_needs_repo(f) : NULL;
  assert(!dbC || (dbC && dbR));
  fsl_free(f->ckout.uuid);
  f->ckout.rid = -1;
  f->ckout.uuid = NULL;
  if(!dbC){
    return 0;
  }
  fsl_cx_err_reset(f);
  rid = fsl_config_get_id(f, FSL_CONFDB_CKOUT, -1, "checkout");
  if(rid>0){
    f->ckout.uuid = fsl_rid_to_uuid(f, rid);
    if(!f->ckout.uuid){
      assert(f->error.code);
      if(!f->error.code){
        rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                            "Could not load UUID for RID %"FSL_ID_T_PFMT,
                            (fsl_id_t)rid);
      }
    }else{
      assert(FSL_UUID_STRLEN==fsl_strlen(f->ckout.uuid));
      rc = 0;
    }
    f->ckout.rid = rid;
  }else if(rid==0){
    /* This is a legal case not possible before libfossil (and only
       afterwards possible in fossil(1)) - an empty repo without an
       active checkin.
    */
    f->ckout.rid = 0;
  }else{
    rc = FSL_RC_NOT_FOUND;
  }
  return rc;
}


void fsl_checkout_version_info(fsl_cx *f, fsl_id_t * rid, fsl_uuid_cstr * uuid ){
  if(uuid) *uuid = f ? f->ckout.uuid : NULL;
  if(rid) *rid = (f && (f->ckout.rid>=0)) ? f->ckout.rid : 0;
}

int fsl_checkout_db_search( char const * dirName, fsl_int_t dirNameLen,
                            char checkParentDirs, fsl_buffer * pOut ){
  int rc;
  fsl_int_t dLen = 0, i;
  static const char aDbName[][10] = { "_FOSSIL_", ".fslckout" };
  fsl_buffer Buf = fsl_buffer_empty;
  fsl_buffer * buf = &Buf;
  enum { DbCount = 2 };
  buf->used = 0;
  if(dirName && (dirNameLen<0)) dirNameLen = (fsl_int_t)fsl_strlen(dirName);
  if(dirName){
    if((0==dirNameLen) || !*dirName) return FSL_RC_RANGE;
    rc = fsl_buffer_append( buf, dirName, dirNameLen );
    if(rc){
      fsl_buffer_clear(buf);
      return rc;
    }
    dLen = dirNameLen;
  }else{
    char zPwd[4000];
    fsl_size_t pwdLen = 0;
    rc = fsl_getcwd( zPwd, sizeof(zPwd)/sizeof(zPwd[0]), &pwdLen );
    if(rc){
      fsl_buffer_clear(buf);
#if 0
      return fsl_cx_err_set(f, rc,
                            "Could not determine current directory. "
                            "Error code %d (%s).",
                            rc, fsl_rc_cstr(rc));
#else
      return rc;
#endif
    }
    if(1 == pwdLen && '/'==*zPwd) *zPwd = '.'
      /* When in the root directory (or chroot) then change dir name
         name to something we can use.
      */
      ;
    rc = fsl_buffer_append(buf, zPwd, pwdLen);
    if(rc){
      fsl_buffer_clear(buf);
      return rc;
    }
    dLen = (fsl_int_t)pwdLen;
  }
  if(rc){
    fsl_buffer_clear(buf);
    return rc;
  }
  assert(buf->capacity>=buf->used);
  assert((buf->used == (fsl_size_t)dLen) || (1==buf->used && (int)'.'==(int)buf->mem[0]));
  assert(0==buf->mem[buf->used]);

  while(dLen>0){
    /*
      Loop over the list in aDbName, appending each one to
      the dir name in the search for something we can use.
    */
    fsl_int_t lenMarker = dLen /* position to
                                  re-set to on each
                                  sub-iteration. */ ;
    /* trim trailing slashes on this part, so that we don't end up
       with multiples between the dir and file in the final output. */
    while( dLen && ((int)'/'==(int)buf->mem[dLen-1])) --dLen;
    for( i = 0; i < DbCount; ++i ){
      char const * zName;
      buf->used = (fsl_size_t)lenMarker;
      dLen = lenMarker;
      rc = fsl_buffer_appendf( buf, "/%s", aDbName[i]);
      if(rc){
        fsl_buffer_clear(buf);
        return rc;
      }
      zName = fsl_buffer_cstr(buf);
      if(0==fsl_file_access(zName, 0)){
        if(pOut) rc = fsl_buffer_append( pOut, buf->mem, buf->used );
        fsl_buffer_clear(buf);
        return rc;
      }
      if(!checkParentDirs){
        dLen = 0;
        break;
      }else{
        /* Traverse up one dir and try again. */
        --dLen;
        while( dLen>0 && (int)buf->mem[dLen]!=(int)'/' ){ --dLen; }
        while( dLen>0 && (int)buf->mem[dLen-1]==(int)'/' ){ --dLen; }
        if(dLen>lenMarker){
          buf->mem[dLen] = 0;
        }
      }
    }
  }
  fsl_buffer_clear(buf);
  return FSL_RC_NOT_FOUND;
}

int fsl_checkout_open_dir( fsl_cx * f, char const * dirName,
                           fsl_int_t dirNameLen, char checkParentDirs ){
  int rc;
  fsl_buffer Buf = fsl_buffer_empty;
  fsl_buffer * buf = &Buf;
  char const * zName;
  if(fsl_cx_db_checkout(f)){
    return fsl_cx_err_set( f, FSL_RC_ACCESS,
                           "A checkout is already opened. "
                           "Close it before opening another.");
  }
  if(dirName && dirNameLen<0){
    dirNameLen = (fsl_int_t)fsl_strlen(dirName);
  }
  rc = fsl_checkout_db_search(dirName, dirNameLen,
                              checkParentDirs, buf);
  if(rc){
    if(FSL_RC_NOT_FOUND==rc){
      rc = fsl_cx_err_set(f, FSL_RC_NOT_FOUND,
                          "Could not find checkout under [%.*s].",
                          dirName ? (int)dirNameLen : (int)1,
                          dirName ? dirName : ".");
    }
    fsl_buffer_clear(buf);
    return rc;
  }
  assert(buf->used>1 /* "/<FILENAME>" */);
  zName = fsl_buffer_cstr(buf);
  rc = fsl_cx_checkout_open_db(f, zName);
  if(rc){
    fsl_buffer_clear(buf);
    return rc;
  }else{
    /* Checkout db is now opened. Fiddle some internal
       bits...
    */
    unsigned char * end = buf->mem+buf->used-1;
    /* Find dir part */
    while(end>buf->mem && (unsigned char)'/'!=*end) --end;
    assert('/' == (char)*end && "fsl_checkout_db_search() appends '/<DBNAME>'");
    fsl_free(f->ckout.dir);
    f->ckout.dirLen = end - buf->mem +1 /* for trailing '/' */ ;
    *(end+1) = 0; /* rather than strdup'ing, we'll just lop off the
                 filename part. Keep the '/' for historical
                 conventions purposes. */
    f->ckout.dir = (char *)buf->mem;
    *buf = fsl_buffer_empty /* we took ownership of buf->mem */;
    assert(!f->ckout.dir[f->ckout.dirLen]);
    assert('/' == f->ckout.dir[f->ckout.dirLen-1]);
    /*defensively drop any existing table definition; there shouldn't be one,
    but maybe could be if the application crashed before closing gracefully*/
    rc = fsl_db_exec( f->dbMain,
                      "DROP TABLE IF EXISTS versionedsettings;");
    if(!rc){
      /*now we create our versioned settings table*/
      /*alas, we must coin the name ourselves, because parameters to CREATE
        VIRTUAL TABLE are not processed by sqlite, so we can't use
        FSL_CKOUT_DIR().  Since we go that far, we might as well just add the
        surrounding sql as well.*/
      rc = fsl_db_exec( f->dbMain,
                        "CREATE VIRTUAL TABLE versionedsettings "
                        "USING VERSIONED_SETTINGS"
                        "( '%q/.fossil-settings', MKDIR );",
                        f->ckout.dir );
    }

    if(!rc){
      /* why?
         rc = fsl_config_open(f, NULL);
             
         Seems to me we don't need that at the library level. In my
         experience global config options for a lib which is used by
         multiple apps are generally a bad idea, as no single
         setting of any given property will be best for all apps.
         Fossil's global config db assumes that there is only one
         fossil-based app, which is no longer the case.
      */
      f->flags |= FSL_CX_F_IS_OPENING_CKOUT;
      rc = fsl_repo_open_for_checkout(f);
      f->flags &= ~FSL_CX_F_IS_OPENING_CKOUT;
      if(!rc){
        /*HHH this updates some copies of settings!!!*/
        rc = fsl_cx_after_open(f);
      }
    }
    if(rc){
      /* Is this sane? Is not doing it sane? */
      fsl_checkout_close(f);
    }
    return rc;
  }
}


char const * fsl_cx_db_file_for_role(fsl_cx const * f,
                                     fsl_db_role_t r,
                                     fsl_size_t * len){
  fsl_db const * db = fsl_cx_db_for_role((fsl_cx*)f, r);
  char const * rc = db ? db->filename : NULL;
  if(len) *len = fsl_strlen(rc);
  return rc;
}

char const * fsl_cx_db_name_for_role(fsl_cx const * f,
                                     fsl_db_role_t r,
                                     fsl_size_t * len){
  if(FSL_DB_ROLE_MAIN == r){
    /* special case to be removed when f->dbMem bits are
       finished. */
    if(len) *len=4;
    return "main";
  }else{
    fsl_db const * db = fsl_cx_db_for_role((fsl_cx*)f, r);
    char const * rc = db ? db->name : NULL;
    if(len) *len = rc ? 0 : fsl_strlen(rc);
    return rc;
  }
}

char const * fsl_cx_db_file_config(fsl_cx const * f,
                                   fsl_size_t * len){
  char const * rc = NULL;
  if(f && f->config.db.filename){
    rc = f->config.db.filename;
    if(len) *len = fsl_strlen(rc);
  }
  return rc;
}

char const * fsl_cx_db_file_repo(fsl_cx const * f,
                                 fsl_size_t * len){
  char const * rc = NULL;
  if(f && f->repo.db.filename){
    rc = f->repo.db.filename;
    if(len) *len = fsl_strlen(rc);
  }
  return rc;
}

char const * fsl_cx_db_file_checkout(fsl_cx const * f,
                                     fsl_size_t * len){
  char const * rc = NULL;
  if(f && f->ckout.db.filename){
    rc = f->ckout.db.filename;
    if(len) *len = fsl_strlen(rc);
  }
  return rc;
}

char const * fsl_cx_checkout_dir_name(fsl_cx const * f,
                                      fsl_size_t * len){
  char const * rc = NULL;
  if(f && f->ckout.dir){
    rc = f->ckout.dir;
    if(len) *len = fsl_strlen(rc);
  }
  return rc;
}

int fsl_cx_flags_get( fsl_cx * f ){
  return f ? f->flags : -1;
}

int fsl_cx_flag_set( fsl_cx * f, int flags, char enable ){
  if(!f) return -1;
  else {
    if(enable) f->flags |= flags;
    else f->flags &= ~flags;
    return f->flags;
  }
}


fsl_xlinker * fsl_xlinker_by_name( fsl_cx * f, char const * name ){

  fsl_xlinker * rv = NULL;
  fsl_size_t i;
  for( i = 0; i < f->xlinkers.used; ++i ){
    rv = f->xlinkers.list + i;
    if(0==fsl_strcmp(rv->name, name)) return rv;
  }
  return NULL;
}

int fsl_xlink_listener( fsl_cx * f, char const * name,
                        fsl_deck_xlink_f cb, void * cbState ){
  fsl_xlinker * x;
  if(!f || !cb || !name || !*name) return FSL_RC_MISUSE;
  x = fsl_xlinker_by_name(f, name);
  if(x){
    /* Replace existing entry */
    x->f = cb;
    x->state = cbState;
    return 0;
  }else if(f->xlinkers.used <= f->xlinkers.capacity){
    /* Expand the array */
    fsl_size_t const n = f->xlinkers.used ? f->xlinkers.used * 2 : 5;
    fsl_xlinker * re =
      (fsl_xlinker *)fsl_realloc(f->xlinkers.list,
                                 n * sizeof(fsl_xlinker));
    if(!re) return FSL_RC_OOM;
    f->xlinkers.list = re;
  }
  x = f->xlinkers.list + f->xlinkers.used++;
  *x = fsl_xlinker_empty;
  x->f = cb;
  x->state = cbState;
  x->name = name;
  return 0;
}

int fsl_cx_user_set( fsl_cx * f, char const * userName ){
  if(!f) return FSL_RC_MISUSE;
  else if(!userName || !*userName){
    fsl_free(f->repo.user);
    f->repo.user = NULL;
    return 0;
  }else{
    char * u = fsl_strdup(userName);
    if(!u) return FSL_RC_OOM;
    else{
      fsl_free(f->repo.user);
      f->repo.user = u;
      return 0;
    }    
  }
}

char const * fsl_cx_user_get( fsl_cx const * f ){
  return f ? f->repo.user : NULL;
}

int fsl_cx_schema_ticket(fsl_cx * f, fsl_buffer * pOut){
  fsl_db * db = f ? fsl_needs_repo(f) : NULL;
  if(!f || !pOut) return FSL_RC_MISUSE;
  else if(!db) return FSL_RC_NOT_A_REPO;
  else{
    fsl_size_t const oldUsed = pOut->used;
    int rc = fsl_config_get_buffer(f, FSL_CONFDB_REPO,
                                   "ticket-table", pOut);
    if((FSL_RC_NOT_FOUND==rc)
       || (oldUsed == pOut->used/*found but it was empty*/)
       ){
      rc = fsl_buffer_append(pOut, fsl_schema_ticket(), -1);
    }
    return rc;
  }
}



int fsl_cx_stat2( fsl_cx * f, char relativeToCwd,
                  char const * zName, fsl_fstat * tgt,
                  fsl_buffer * nameOut, char fullPath){
  int rc;
  fsl_buffer * b = f ? &f->fsScratch : NULL;
  fsl_buffer bufRel = fsl_buffer_empty;
  fsl_size_t n;
  if(!f || !zName || !*zName) return FSL_RC_MISUSE;
  else if(!f->ckout.dir) return FSL_RC_NOT_A_CHECKOUT;
#if 1
  else{
    rc = fsl_checkout_filename_check(f, relativeToCwd, zName, &bufRel);
    if(rc) goto end;
    zName = fsl_buffer_cstr2( &bufRel, &n );
  }
#else
  else if(!fsl_is_simple_pathname(zName, 1)){
    rc = fsl_checkout_filename_check(f, relativeToCwd, zName, &bufRel);
    if(rc) goto end;
    zName = fsl_buffer_cstr2( &bufRel, &n );
    /* MARKER(("bufRel=%s\n",zName)); */
  }else{
    n = fsl_strlen(zName);
  }
#endif
  assert(n>0 &&
         "Will fail if fsl_checkout_filename_check() changes "
         "to return nothing if zName==checkout root");
  assert(b->used==0 && "Someone did not re-set f->fsScratch OR it is in use higher up the stack.");
  assert(b->capacity && "We expected this to be set up by fsl_checkout_filename_check()");
  if(!n
     /* i don't like the "." resp "./" result when zName==checkout root */
     || (1==n && '.'==bufRel.mem[0])
     || (2==n && '.'==bufRel.mem[0] && '/'==bufRel.mem[1])){
    rc = fsl_buffer_appendf(b, "%s%s", f->ckout.dir,
                            (2==n) ? "/" : "");
  }else{
    rc = fsl_buffer_appendf(b, "%s%s", f->ckout.dir, zName);
  }
  if(!rc){
    rc = fsl_stat( fsl_buffer_cstr(b), tgt, 1 );
    if(rc){
      fsl_cx_err_set(f, rc, "Error %s from fsl_stat(%b)",
                     fsl_rc_cstr(rc), b);
    }else if(nameOut){
      rc = fullPath
        ? fsl_buffer_append(nameOut, b->mem, b->used)
        : fsl_buffer_append(nameOut, zName, n);
    }
  }
  end:
  b->used = 0;
  fsl_buffer_clear(&bufRel);
  return rc;
}

int fsl_cx_stat(fsl_cx * f, char relativeToCwd, char const * zName,
                fsl_fstat * tgt){
  return fsl_cx_stat2(f, relativeToCwd, zName, tgt, NULL, 0);
}


void fsl_cx_case_sensitive_set(fsl_cx * f, char caseSensitive){
  if(f){
    f->cache.caseInsensitive = caseSensitive ? 0 : 1;
  }
}

char fsl_cx_is_case_sensitive(fsl_cx const * f){
  return f ? !f->cache.caseInsensitive : 0;
}

char const * fsl_cx_filename_collation(fsl_cx const * f){
  return (f && f->cache.caseInsensitive)
    ? "COLLATE nocase" : "";
}


void fsl_cx_yield_file_buffer(fsl_cx * f){
  enum { MaxSize = 1024 * 1024 * 2 };
  assert(f);
  if(f->fileContent.capacity>MaxSize){
    fsl_buffer_resize(&f->fileContent, MaxSize);
    assert(f->fileContent.capacity<=MaxSize+1);
  }
  f->fileContent.used = 0;
}

fsl_error const * fsl_cx_err_get_e(fsl_cx const * f){
  return f ? &f->error : NULL;
}

void fsl_cx_close_dbs( fsl_cx * f ){
  if(!f) return;
  else{
    int const errCheck = f->error.code;
    fsl_repo_close(f);
    fsl_checkout_close(f);
    fsl_config_close(f);
    assert(!f->repo.db.dbh);
    assert(!f->ckout.db.dbh);
    assert(!f->config.db.dbh);
    if(!errCheck && f->error.code){
      /* The error state was clean before we started but one of the
         above updated it. Suppress the error.
      */
      fsl_cx_err_reset(f);
    }
  }
}

char const * fsl_cx_glob_matches( fsl_cx * f, int gtype,
                                  char const * str ){
  int i, count = 0;
  char const * rv = NULL;
  fsl_list const * lists[] = {0,0,0};
  if(!f || !str || !*str) return NULL;
  if(gtype & FSL_GLOBS_IGNORE) lists[count++] = &f->cache.globs.ignore;
  if(gtype & FSL_GLOBS_CRNL) lists[count++] = &f->cache.globs.crnl;
  /*CRNL/BINARY together makes little sense, but why strictly prohibit
    it?*/
  if(gtype & FSL_GLOBS_BINARY) lists[count++] = &f->cache.globs.binary;
  for( i = 0; i < count; ++i ){
    if( (rv = fsl_glob_list_matches( lists[i], str )) ) break;
  }
  return rv;
}

int fsl_output_f_fsl_cx(void * state, void const * src, fsl_size_t n ){
  return (state && src && n)
    ? fsl_output((fsl_cx*)state, src, n)
    : (n ? FSL_RC_MISUSE : 0);
}

#if 0
struct tm * fsl_cx_localtime( fsl_cx const * f, const time_t * clock ){
  if(!clock) return NULL;
  else if(!f) return localtime(clock);
  else return (f->flags & FSL_CX_F_LOCALTIME_GMT)
         ? gmtime(clock)
         : localtime(clock)
         ;
}

struct tm * fsl_localtime( const time_t * clock ){
  return fsl_cx_localtime(NULL, clock);
}

time_t fsl_cx_time_adj(fsl_cx const * f, time_t clock){
  struct tm * tm = fsl_cx_localtime(f, &clock);
  return tm ? mktime(tm) : 0;
}
#endif

#undef MARKER
