/** @file  pmConfig.h
 *
 *  @author PAP (IfA)
 *  @author EAM (IfA)
 *
 *  @version $Revision: 1.76 $ $Name: not supported by cvs2svn $
 *  @date $Date: 2007-01-30 00:05:16 $
 *
 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <libgen.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <glob.h>
#include <pslib.h>

#include "pmConfig.h"
#include "pmErrorCodes.h"
#include "pmConfigRecipes.h"
#include "pmConfigCamera.h"

#ifdef HAVE_NEBCLIENT
#include <nebclient.h>
#endif // ifdef HAVE_NEBCLIENT

#define PS_SITE "PS_SITE"         // Name of the environment variable containing the site config file
#define PS_DEFAULT_SITE ".ipprc"  // Default site config file

static bool readCameraConfig = true;    // Read the camera config on startup (with pmConfigRead)?
static psArray *configPath = NULL;      // Search path for configuration files

bool pmConfigReadParamsSet(bool newReadCameraConfig)
{
    bool oldReadCameraConfig = readCameraConfig;
    readCameraConfig = newReadCameraConfig;
    return oldReadCameraConfig;
}

static void configFree(pmConfig *config)
{
    psFree(config->site);
    psFree(config->files);
    psFree(config->camera);
    psFree(config->cameraName);
    psFree(config->format);
    psFree(config->formatName);
    psFree(config->recipes);
    psFree(config->recipeSymbols);
    psFree(config->arguments);
    psFree(config->database);
}

pmConfig *pmConfigAlloc(int *argc, char **argv)
{
    pmConfig *config = psAlloc(sizeof(pmConfig));
    (void)psMemSetDeallocator(config, (psFreeFunc)configFree);

    // Initialise
    config->site = NULL;
    config->camera = NULL;
    config->cameraName = NULL;
    config->format = NULL;
    config->formatName = NULL;
    config->recipes = psMetadataAlloc();
    config->recipesRead = PM_RECIPE_SOURCE_NONE;
    config->recipeSymbols = psMetadataAlloc();
    config->arguments = psMetadataAlloc();
    config->database = NULL;
    config->argc = argc;
    config->argv = argv;
    config->defaultRecipe = NULL;

    // the file structure is used to carry pmFPAfiles
    config->files = psMetadataAlloc ();
    return config;
}

// Resolve environment variables within a directory name; returns the resolved directory string.
// The returned string is likely a new pointer; the old pointer should be freed by psStringSubstitute.
static psString resolveEnvVar(psString dir // Directory to check for environment variables
                             )
{
    char *envStart;                     // Start of any environment variable
    while ((envStart = strchr(dir, '$'))) {
        char *envName = envStart + 1;   // Start of the environment variable name
        if (envName[0] == '\0') {
            psError(PS_ERR_BAD_PARAMETER_VALUE, true, "Path %s contains a bad environment variable.\n", dir);
            return NULL;
        }
        if (envName[0] == '{') {
            envName++;
            if (envName[0] == '\0') {
                psError(PS_ERR_BAD_PARAMETER_VALUE, true,
                        "Path %s contains a bad environment variable.\n", dir);
                return NULL;
            }
        }
        char *envStop = strpbrk(envStart, "}/"); // End of the environment variable
        ssize_t nameLength = envStop ? envStop - envName : strlen(envName); // Length of the name
        psString name = psStringNCopy(envName, nameLength); // The environment variable name
        char *value = getenv(name);     // Value of the environment variable
        psFree(name);
        psString valueSlash = NULL;    // Value with appended slash
        psStringAppend(&valueSlash, "%s/", value);

        ssize_t envvarLength = envStop ? envStop - envStart : strlen(envStart); // Length, w/o '}'
        psString envvar = psStringNCopy(envStart, envvarLength + 1);  // Environment variable, with $, {, }

        psTrace("psModules.config", 7, "Replacing %s with %s in directory %s\n", envvar, valueSlash, dir);
        psStringSubstitute(&dir, valueSlash, envvar);
        psFree(envvar);
        psFree(valueSlash);
    }

    return dir;
}

void pmConfigSet(const char *path)
{
    pmConfigDone();

    psList *list = psStringSplit(path, ":", false);
    configPath = psListToArray(list);
    // Resolve environment variables
    for (long i = 0; i < configPath->n; i++) {
        configPath->data[i] = resolveEnvVar(configPath->data[i]);
        psTrace("psModules.config", 4, "Path %ld: %s\n", i, (char*)configPath->data[i]);
    }
    psFree(list);
}

void pmConfigDone(void)
{
    psFree(configPath);
    configPath = NULL;
}

bool pmConfigFileRead(psMetadata **config, const char *name, const char *description)
{
    PS_ASSERT_PTR_NON_NULL(config, false);
    PS_ASSERT_STRING_NON_EMPTY(name, false);
    PS_ASSERT_STRING_NON_EMPTY(description, false);

    char *realName = NULL;
    unsigned int numBadLines = 0;
    struct stat filestat;

    psTrace("psModules.config", 3, "Loading %s configuration from file %s\n",
            description, name);

    uid_t uid = getuid();
    gid_t gid = getgid();

    // we try: name, path[0]/name, path[1]/name, ...
    // find the first existing entry in the path (starting with the bare name)
    realName = psStringCopy (name);
    psTrace ("psModules.config", 8, "trying %s\n", realName);

    int status = stat (realName, &filestat);
    if (status == 0) {
        if ((uid == filestat.st_uid) && (filestat.st_mode & S_IRUSR)) {
            goto found;
        }
        if ((gid == filestat.st_gid) && (filestat.st_mode & S_IRGRP)) {
            goto found;
        }
        if (filestat.st_mode & S_IROTH) {
            goto found;
        }
    }
    psFree (realName);

    if (configPath == NULL) {
        psError(PS_ERR_IO, true, "Cannot find %s configuration file (%s) in path\n", description, name);
        return false;
    }

    for (int i = 0; i < configPath->n; i++) {
        realName = psStringCopy (configPath->data[i]);
        psStringAppend (&realName, "/%s", name);
        psTrace ("psModules.config", 8, "trying %s\n", realName);

        status = stat (realName, &filestat);
        if (status == 0) {
            if ((uid == filestat.st_uid) && (filestat.st_mode & S_IRUSR)) {
                goto found;
            }
            if ((gid == filestat.st_gid) && (filestat.st_mode & S_IRGRP)) {
                goto found;
            }
            if (filestat.st_mode & S_IROTH) {
                goto found;
            }
        }
        psFree (realName);
    }

    psError(PS_ERR_IO, true, "Cannot find %s configuration file %s in path\n", description, name);
    return false;

found:
    *config = psMetadataConfigRead(NULL, &numBadLines, realName, true);
    if (numBadLines > 0) {
        psError(PS_ERR_IO, false, "%d bad lines in %s configuration file (%s)",
                numBadLines, description, realName);
        psFree (realName);

        return false;
    }
    if (!*config) {
        psError(PS_ERR_IO, true, "Unable to read %s configuration from %s",
                description, realName);
        psFree (realName);
        return false;
    }

    psFree (realName);
    return true;
}

// Read metadata config files in a metadata
// The metadata contains file names, which will be replaced with the metadata that are in the files.
static bool metadataReadFiles(psMetadata *source, // Source metadata
                              const char *description // Description, for error messages
                             )
{
    assert(source);
    psMetadataIterator *iter = psMetadataIteratorAlloc(source, PS_LIST_HEAD, NULL); // Iterator
    psMetadataItem *item;               // Item from iteration
    while ((item = psMetadataGetAndIncrement(iter))) {
        if (item->type == PS_DATA_METADATA) {
            continue;       // We've already read it
        }
        if (item->type != PS_DATA_STRING) {
            psError(PS_ERR_BAD_PARAMETER_TYPE, true, "Element %s in %s metadata is not of type STR.\n",
                    item->name, description);
            continue;
        }

        psTrace("config", 2, "Reading %s %s: %s\n", description, item->name, item->data.str);
        psMetadata *new = NULL;         // New metadata
        if (!pmConfigFileRead(&new, item->data.str, item->name)) {
            psLogMsg("psModules.config", PS_LOG_WARN, "Trouble reading reading %s %s --- "
                     "ignored.\n", description, item->name);
            psFree(new);
            psMetadataRemoveKey(source, item->name); // Take it out, so it will not trouble us again
            continue;
        }

        // Muck around under the hood to replace the filename with the metadata; don't try this at home, kids
        item->type = PS_DATA_METADATA;
        psFree(item->data.str);
        item->data.md = new;
    }
    psFree(iter);

    return true;
}

// Read the formats for a camera
static bool cameraReadFormats(psMetadata *camera, // Camera for which to read the formats
                              const char *name // Name of the camera, for error messages
                             )
{
    assert(camera);
    assert(name);

    bool mdok;                          // Status of MD lookup
    psMetadata *formats = psMetadataLookupMetadata(&mdok, camera, "FORMATS"); // Formats
    if (!mdok || !formats) {
        psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find FORMATS in camera configuration %s.\n", name);
        return false;
    }
    if (!metadataReadFiles(formats, "camera format")) {
        psError(PS_ERR_UNKNOWN, false, "Unable to read formats within camera configuration %s.\n", name);
        return false;
    }

    return true;
}


pmConfig *pmConfigRead(int *argc, char **argv, char *defaultRecipe)
{
    PS_ASSERT_PTR_NON_NULL(argc, NULL);
    PS_ASSERT_INT_POSITIVE(*argc, NULL);
    PS_ASSERT_PTR_NON_NULL(argv, NULL);

    pmConfig *config = pmConfigAlloc(argc, argv); // The configuration, containing site, camera and recipes
    config->defaultRecipe = defaultRecipe;

    //
    // The following section of code attempts to determine which file is
    // the configuration file.  At the end of this code block, the siteName
    // variable will contain the name of the configuration file.
    //
    char *siteName = NULL;
    //
    // First, try command line
    //
    psS32 argNum = psArgumentGet(*config->argc, config->argv, "-site");
    if (argNum != 0) {
        //
        // We remove the "-site" argument from argv.  Then
        // we look for the next argument, which should be the filename, and
        // remove it as well.
        //
        psArgumentRemove(argNum, config->argc, config->argv);
        if (argNum >= *config->argc) {
            psLogMsg("psModules.config", PS_LOG_WARN,
                     "-site command-line switch provided without the required filename --- ignored.\n");
        } else {
            siteName = psStringCopy(config->argv[argNum]);
            psArgumentRemove(argNum, config->argc, config->argv);
        }
    }
    //
    // Next, try environment variable
    //
    if (!siteName) {
        siteName = getenv(PS_SITE);
        if (siteName) {
            siteName = psStringCopy (siteName);
        }
    }

    //
    // Last chance is ~/.ipprc
    //
    if (!siteName) {
        char *home = getenv("HOME");
        siteName = psStringCopy(home);
        psStringAppend(&siteName, "/%s", PS_DEFAULT_SITE);
    }


    // We have the configuration filename; now we read and parse the config
    // file and store in psMetadata struct site.
    //

    if (!pmConfigFileRead(&config->site, siteName, "site")) {
        psFree(config);
        return NULL;
    }

    // Set options based on the site configuration.
    {
        bool mdok = true;   // Status of MD lookup result

        // Initialise the psLib time handling
        psString timeName = psMetadataLookupStr(&mdok, config->site, "TIME");
        if (mdok && timeName)
        {
            psTrace("psModules.config", 7, "Initialising psTime with file %s\n", timeName);
            // XXX: PAP had a call to psLibInit is PRODUCTION not set.  Why?
            psTimeInitialize(timeName);
        }


        // Set logging level
        int logLevel = psMetadataLookupS32(&mdok, config->site, "LOGLEVEL");
        if (mdok && logLevel >= 0)
        {
            psTrace("psModules.config", 7, "Setting log level to %d\n", logLevel);
            psLogSetLevel(logLevel);
        }


        // Set logging format
        psString logFormat = psMetadataLookupStr(&mdok, config->site, "LOGFORMAT");
        if (mdok && logFormat)
        {
            psTrace("psModules.config", 7, "Setting log format to %s\n", logFormat);
            psLogSetFormat(logFormat);
        }

        argNum = psArgumentGet(*config->argc, config->argv, "-log");
        if (argNum > 0)
        {
            psArgumentRemove(argNum, config->argc, config->argv);
            if (argNum >= *config->argc) {
                psLogMsg("psModules.config", PS_LOG_WARN, "-log command-line switch provided without the "
                         "required log destination --- ignored.\n");
            } else {
                if (!psLogSetDestination(psMessageDestination(config->argv[argNum]))) {
                    psLogMsg("psModules.config", PS_LOG_WARN, "Unable to set log destination to %s\n",
                             config->argv[argNum]);
                }
                psArgumentRemove(argNum, config->argc, config->argv);
            }
        } else
        {
            // Set logging destination
            psString logDest = psMetadataLookupStr(&mdok, config->site, "LOGDEST");
            if (mdok && logDest && strlen(logDest) > 0) {
                // XXX: Only stdout and stderr are provided for now; this section should be
                // expanded in the future to do files, and perhaps even sockets.
                if (!psLogSetDestination(psMessageDestination(logDest))) {
                    psLogMsg("psModules.config", PS_LOG_WARN, "Unable to set log destination to %s\n",
                             config->argv[argNum]);
                }
            }
        }

        // Set trace levels
        psMetadata *trace = psMetadataLookupMetadata(&mdok, config->site, "TRACE");
        if (mdok && trace)
        {
            psMetadataIterator *traceIter = psMetadataIteratorAlloc(trace, PS_LIST_HEAD, NULL); // Iterator
            psMetadataItem *traceItem = NULL; // Item from MD iteration
            while ((traceItem = psMetadataGetAndIncrement(traceIter))) {
                if (traceItem->type != PS_DATA_S32) {
                    psLogMsg("psModules.config", PS_LOG_WARN,
                             "The level for trace component %s is not of type S32 (%x)\n",
                             traceItem->name, traceItem->type);
                    continue;
                }
                psTrace("psModules.config", 7, "Setting trace level for %s to %d\n", traceItem->name,
                        traceItem->data.S32);
                psTraceSetLevel(traceItem->name, traceItem->data.S32);
            }
            psFree(traceIter);
        }

        // Set trace formats
        psString traceFormat = psMetadataLookupStr(&mdok, config->site, "TRACEFORMAT");
        if (mdok && traceFormat)
        {
            psTrace("psModules.config", 7, "Setting trace format to %s\n", traceFormat);
            psTraceSetFormat(traceFormat);
        }

        // Set trace destinations
        #ifndef PS_NO_TRACE
        psString traceDest = psMetadataLookupStr(&mdok, config->site, "TRACEDEST");
        if (mdok && traceDest && strlen(traceDest) > 0)
        {
            psTrace("psModules.config", 7, "Setting trace destination to %s\n", traceDest);
            // XXX: Only stdout and stderr are provided for now; this section should be
            // expanded in the future to do files, and perhaps even sockets.
            if (!psTraceSetDestination(psMessageDestination(traceDest))) {
                psLogMsg("psModules.config", PS_LOG_WARN, "Unable to set trace destination to %s\n", traceDest);

            }
        }
        #endif

        // Allow command line options to override defaults for logging.
        // XXX: Is it appropriate to use the ArgVerbosity function for this?
        //   A: it removes the options from the command line.
        //   B: will the pmConfigRead function always be called on initialization.
        //
        psArgumentVerbosity(config->argc, config->argv);
        // XXX: substitute the string for the default log level for "2".
    }

    // define the config-file search path (configPath).  Ensure that
    // it contains the directory where we found the config file in
    // the first place
    if (configPath) {
        pmConfigDone();
    }

    psString siteNameDir = psStringCopy(dirname(siteName));
    psFree(siteName);

    psString path = psMetadataLookupStr(NULL, config->site, "PATH");
    if (path) {
        psStringAppend(&path, ":%s", siteNameDir);
    } else {
        path = psMemIncrRefCounter(siteNameDir);
    }
    pmConfigSet(path);
    psFree(siteNameDir);

    // Next, we do a similar thing for the camera configuration file.  The
    // file is read and parsed into psMetadata struct "camera".
    //
    argNum = psArgumentGet(*config->argc, config->argv, "-camera");
    if (argNum > 0) {
        psArgumentRemove(argNum, config->argc, config->argv);
        if (argNum >= *config->argc) {
            psLogMsg("psModules.config", PS_LOG_WARN,
                     "-camera command-line switch provided without the required camera or filename --- "
                     "ignored.\n");
        } else {
            char *cameraFile = config->argv[argNum]; // The camera configuration file to read

            // look for a symbolic camera name in the CAMERAS metadata
            // otherwise fall back to trying the -camera option as a literal
            // filename
            bool mdok = true;           // Status of MD lookup
            psMetadata *cameras = psMetadataLookupMetadata(&mdok, config->site, "CAMERAS");
            if (mdok && cameras) {
                char *newFile = psMetadataLookupStr(NULL, cameras, cameraFile); // The filename
                if (newFile) {
                    cameraFile = newFile;
                }
            } else {
                psError(PS_ERR_IO, false, "Unable to find CAMERAS in site configuration.\n");
                psFree(config);
                return NULL;
            }

            pmConfigFileRead(&config->camera, cameraFile, "camera");
            psArgumentRemove(argNum, config->argc, config->argv);

            // Read in the formats
            if (!cameraReadFormats(config->camera, cameraFile)) {
                psError(PS_ERR_UNKNOWN, false, "Unable to read formats within camera configuration %s.\n",
                        cameraFile);
                psFree(config);
                return NULL;
            }

            psMetadataAddMetadata(cameras, PS_LIST_HEAD, cameraFile, PS_META_REPLACE,
                                  "Camera specified on command line", config->camera);

            if (!pmConfigCameraMosaickedVersions(config->site, cameraFile)) {
                psError(PS_ERR_UNKNOWN, false,
                        "Unable to generate mosaicked versions of specified camera %s.\n",
                        cameraFile);
                psFree(config);
                return NULL;
            }
        }
    }

    // Read the camera configurations, if not already defined, and not turned off
    if (!config->camera && readCameraConfig) {
        bool mdok;                      // Status of MD lookup
        psMetadata *cameras = psMetadataLookupMetadata(&mdok, config->site, "CAMERAS"); // List of cameras
        if (!mdok || !cameras) {
            psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find CAMERAS in the site configuration.\n");
            return false;
        }

        if (!metadataReadFiles(cameras, "camera configuration")) {
            psError(PS_ERR_UNKNOWN, false, "Unable to read cameras within site configuration.\n");
            psFree(config);
            return NULL;
        }

        // Now fill in the formats
        psMetadataIterator *iter = psMetadataIteratorAlloc(cameras, PS_LIST_HEAD, NULL); // Iterator
        psMetadataItem *item;           // Item from iteration
        while ((item = psMetadataGetAndIncrement(iter))) {
            assert(item->type == PS_DATA_METADATA);
            if (!cameraReadFormats(item->data.md, item->name)) {
                psWarning("Unable to read formats for camera %s: removed.\n", item->name);
                psMetadataRemoveKey(cameras, item->name);
            }
        }
        psFree(iter);

        if (!pmConfigCameraMosaickedVersionsAll(config->site)) {
            psError(PS_ERR_UNKNOWN, false, "Unable to generate mosaicked versions of cameras.\n");
            psFree(config);
            return NULL;
        }
    }

    // Load the recipes from the camera file, if appropriate
    if(!pmConfigReadRecipes(config, PM_RECIPE_SOURCE_SITE | PM_RECIPE_SOURCE_CAMERA)) {
        psError(PS_ERR_IO, false, "Failed to read recipes from camera file");
        psFree(config);
        return NULL;
    }

    // load command-line options of the form -recipe NAME RECIPE
    pmConfigLoadRecipeArguments(config);

    // read in command-line options to specific recipe values
    pmConfigLoadRecipeOptions(config, "-D");
    pmConfigLoadRecipeOptions(config, "-Di");
    pmConfigLoadRecipeOptions(config, "-Df");
    pmConfigLoadRecipeOptions(config, "-Db");


    // check for values that override DB* keywords
    argNum = psArgumentGet(*config->argc, config->argv, "-dbserver");
    if (argNum > 0) {
        psArgumentRemove(argNum, config->argc, config->argv);
        if (argNum >= *config->argc) {
            psLogMsg("psModules.config", PS_LOG_WARN,
                     "-dbserver command-line switch provided without the required server name --- ");
        } else {
            char *dbserver = config->argv[argNum]; // The camera configuration file to read
            if (!psMetadataAddStr(config->site, PS_LIST_TAIL, "DBSERVER", PS_META_REPLACE, NULL, dbserver)) {
                psLogMsg("psModules.config", PS_LOG_WARN,
                         "failed to overwrite .ipprc DBSERVER value --- ");
            }

            psArgumentRemove(argNum, config->argc, config->argv);
        }
    }

    argNum = psArgumentGet(*config->argc, config->argv, "-dbname");
    if (argNum > 0) {
        psArgumentRemove(argNum, config->argc, config->argv);
        if (argNum >= *config->argc) {
            psLogMsg("psModules.config", PS_LOG_WARN,
                     "-dbname command-line switch provided without the required database name --- ");
        } else {
            char *dbname = config->argv[argNum]; // The camera configuration file to read
            if (!psMetadataAddStr(config->site, PS_LIST_TAIL, "DBNAME", PS_META_REPLACE, NULL, dbname)) {
                psLogMsg("psModules.config", PS_LOG_WARN,
                         "failed to overwrite .ipprc DBNAME value --- ");
            }

            psArgumentRemove(argNum, config->argc, config->argv);
        }
    }

    argNum = psArgumentGet(*config->argc, config->argv, "-dbuser");
    if (argNum > 0) {
        psArgumentRemove(argNum, config->argc, config->argv);
        if (argNum >= *config->argc) {
            psLogMsg("psModules.config", PS_LOG_WARN,
                     "-dbuser command-line switch provided without the required database name --- ");
        } else {
            char *dbuser = config->argv[argNum]; // The camera configuration file to read
            if (!psMetadataAddStr(config->site, PS_LIST_TAIL, "DBUSER", PS_META_REPLACE, NULL, dbuser)) {
                psLogMsg("psModules.config", PS_LOG_WARN,
                         "failed to overwrite .ipprc DBUSER value --- ");
            }

            psArgumentRemove(argNum, config->argc, config->argv);
        }
    }

    argNum = psArgumentGet(*config->argc, config->argv, "-dbpassword");
    if (argNum > 0) {
        psArgumentRemove(argNum, config->argc, config->argv);
        if (argNum >= *config->argc) {
            psLogMsg("psModules.config", PS_LOG_WARN,
                     "-dbpassword command-line switch provided without the required password --- ");
        } else {
            char *dbpassword = config->argv[argNum]; // The camera configuration file to read
            if (!psMetadataAddStr(config->site, PS_LIST_TAIL, "DBPASSWORD", PS_META_REPLACE, NULL, dbpassword)) {
                psLogMsg("psModules.config", PS_LOG_WARN,
                         "failed to overwrite .ipprc DBPASSWORD value --- ");
            }

            psArgumentRemove(argNum, config->argc, config->argv);
        }
    }

    argNum = psArgumentGet(*config->argc, config->argv, "-dbport");
    if (argNum > 0) {
        psArgumentRemove(argNum, config->argc, config->argv);
        if (argNum >= *config->argc) {
            psLogMsg("psModules.config", PS_LOG_WARN,
                     "-dbpport command-line switch provided without the required port number --- ");
        } else {
            char *dbport = config->argv[argNum]; // The camera configuration file to read
            if (!psMetadataAddS32(config->site, PS_LIST_TAIL, "DBPORT", PS_META_REPLACE, NULL, (psS32)atoi(dbport))) {
                psLogMsg("psModules.config", PS_LOG_WARN,
                         "failed to overwrite .ipprc DBPORT value --- ");
            }

            psArgumentRemove(argNum, config->argc, config->argv);
        }
    }


    psErrorClear();   // we may have failed to find some items in the metadata

    return config;
}


// XXX aren't these (return false) below errors: call psError?
bool pmConfigValidateCameraFormat(bool *valid, const psMetadata *cameraFormat, const psMetadata *header)
{
    PS_ASSERT_PTR_NON_NULL(cameraFormat, false);
    PS_ASSERT_PTR_NON_NULL(header, false);

    // Read the rule for that camera format
    bool mdStatus = true;

    psMetadata *rule = psMetadataLookupMetadata(&mdStatus, cameraFormat, "RULE");
    if (! mdStatus || ! rule) {
        psError(PS_ERR_UNKNOWN, false, "Unable to read rule for camera.");
        *valid = false;
        return false;
    }

    // Apply the rules
    psMetadataIterator *ruleIter = psMetadataIteratorAlloc(rule, PS_LIST_HEAD, NULL); // Rule iterator
    psMetadataItem *ruleItem = NULL;    // Item from the metadata

    *valid = true;
    while (*valid && (ruleItem = psMetadataGetAndIncrement(ruleIter))) {
        // Check for the existence of the rule
        psMetadataItem *headerItem = psMetadataLookup(header, ruleItem->name);
        if (! headerItem) {
            // rule item not found in header
            psTrace("psModules.config", 5, "Can't find %s", ruleItem->name);
            *valid = false;
        }

        // Check to see if the rule works
        if (headerItem && !psMetadataItemCompare(headerItem, ruleItem)) {
            psTrace("psModules.config", 5, "%s doesn't match.", ruleItem->name);
            *valid = false;
        }
    } // Iterating through the RULEs

    psFree(ruleIter);
    return true;
}

// Given a camera and a header, see if any of the camera formats match the header
static bool formatFromHeader(psMetadata **format, // Format to return
                             psString *name, // Name to return
                             psMetadata *camera, // Camera configuration
                             const psMetadata *header, // FITS header
                             const char *cameraName // Name of camera
                            )
{
    assert(format);
    assert(camera);
    assert(header);
    assert(cameraName && strlen(cameraName) > 0);

    bool result = false;                // Did we find the first match?

    // Read the list of formats
    bool mdok = true;                   // Status of MD lookup
    psMetadata *formats = psMetadataLookupMetadata(&mdok, camera, "FORMATS"); // List of formats
    if (!mdok || !formats) {
        psError(PS_ERR_UNKNOWN, false, "Unable to find list of FORMATS in camera %s", cameraName);
        return false;
    }

    if (!metadataReadFiles(formats, "camera format")) {
        psError(PS_ERR_UNKNOWN, false, "Unable to read cameras formats within camera configuration.\n");
        return false;
    }

    // Iterate over the formats
    psMetadataIterator *formatsIter = psMetadataIteratorAlloc(formats, PS_LIST_HEAD, NULL);
    psMetadataItem *formatsItem = NULL; // Item from formats
    while ((formatsItem = psMetadataGetAndIncrement(formatsIter))) {
        assert(formatsItem->type == PS_DATA_METADATA); // Since we have just read it in or deleted it
        psMetadata *testFormat = formatsItem->data.md; // Format to test against

        psTrace("psModules.config", 5, "trying format %s", formatsItem->name);

        bool valid = false;
        if (!pmConfigValidateCameraFormat(&valid, testFormat, header)) {
            psError (PS_ERR_UNKNOWN, false, "Error in config scripts for camera %s, format %s\n",
                     cameraName, formatsItem->name);
            return false;
        }
        if (valid) {
            if (!*format) {
                psLogMsg("psModules.config", PS_LOG_INFO, "Camera %s, format %s matches header.\n",
                         cameraName, formatsItem->name);
                *format = psMemIncrRefCounter(testFormat);
                *name = psStringCopy(formatsItem->name);
                result = true;
            } else {
                psLogMsg("psModules.config", PS_LOG_WARN,
                         "Camera %s, format %s also matches header --- ignored.\n",
                         cameraName, formatsItem->name);
            }
        }
    }
    psFree(formatsIter);
    return result;
}


psMetadata *pmConfigCameraFormatFromHeader(pmConfig *config, const psMetadata *header)
{
    PS_ASSERT_PTR_NON_NULL(config, NULL);
    PS_ASSERT_PTR_NON_NULL(header, NULL);

    psMetadata *format = NULL;          // The winning format
    psString name = NULL;               // Name of the winning format

    // If we don't know what sort of camera we have, we try all that we know
    if (! config->camera) {
        bool mdok;                      // Metadata lookup status
        psMetadata *cameras = psMetadataLookupMetadata(&mdok, config->site, "CAMERAS");
        if (! mdok || !cameras) {
            psError(PS_ERR_IO, true, "Unable to find CAMERAS in the configuration.");
            return NULL;
        }

        if (!metadataReadFiles(cameras, "camera configuration")) {
            psError(PS_ERR_UNKNOWN, false, "Unable to read cameras within site configuration.\n");
            return NULL;
        }

        // Iterate over the cameras
        psMetadataIterator *camerasIter = psMetadataIteratorAlloc(cameras, PS_LIST_HEAD, NULL);
        psMetadataItem *camerasItem = NULL; // Item from the metadata
        while ((camerasItem = psMetadataGetAndIncrement(camerasIter))) {
            // Open the camera information
            psTrace("psModules.config", 3, "Inspecting camera %s (%s)\n", camerasItem->name,
                    camerasItem->comment);
            assert(camerasItem->type == PS_DATA_METADATA); // It should be because we've read it in or deleted
            psMetadata *testCamera = camerasItem->data.md; // Camera to test against what we've got:
            if (formatFromHeader(&format, &name, testCamera, header, camerasItem->name)) {
                config->camera = psMemIncrRefCounter(testCamera);
                config->cameraName = psStringCopy(camerasItem->name);
                config->formatName = name;
                config->format = format;
            } else {
                psErr *error = psErrorLast();
                if (error->code != PS_ERR_NONE) {
                    psError(PS_ERR_IO, false, "Error reading camera config data for %s", camerasItem->name);
                    return NULL;
                }
                psFree(error);
            }
        } // Done looking at all cameras
        psFree(camerasIter);

        if (! config->camera) {
            psError(PS_ERR_IO, false, "Unable to find a camera that matches input FITS header!");
            return NULL;
        }

        // Now we have the camera, we can read the recipes
        pmConfigReadRecipes(config, PM_RECIPE_SOURCE_CAMERA | PM_RECIPE_SOURCE_CL);
        return psMemIncrRefCounter(format);
    }

    // Otherwise, try the specific camera
    if (!formatFromHeader(&format, &name, config->camera, header, config->cameraName)) {
        psError(PS_ERR_IO, true, "Unable to find a format with the specified camera (%s) that matches the "
                "given header.\n", config->cameraName);
        return NULL;
    }

    // Free the format and name just in case they've already been allocated
    if (config->format || config->formatName) {
        if (config->format != format || strcmp(config->formatName, name) != 0) {
            psWarning("Default camera format configuration has changed!\n");
        }
        psFree(config->format);
        psFree(config->formatName);
    }
    config->formatName = name;
    config->format = format;
    return psMemIncrRefCounter(format);
}

// Return the requested camera configuration
psMetadata *pmConfigCameraByName(pmConfig *config, const char *cameraName)
{
    PS_ASSERT_PTR_NON_NULL(config, NULL);
    PS_ASSERT_STRING_NON_EMPTY(cameraName, NULL);

    psMetadata *cameras = psMetadataLookupMetadata(NULL, config->site, "CAMERAS");
    if (!cameras) {
        psError(PS_ERR_IO, true, "Unable to find CAMERAS in the configuration.");
        return NULL;
    }

    char *cameraPath = psMetadataLookupStr(NULL, cameras, cameraName);
    if (!cameraPath) {
        psError(PS_ERR_IO, true, "Unable to find requested CAMERA in the configuration.");
        return NULL;
    }

    psMetadata *camera = NULL; // Camera to test against what we've got:

    if (!pmConfigFileRead(&camera, cameraPath, cameraName)) {
        psLogMsg("psModules.config", PS_LOG_WARN, "Trouble reading reading camera configuration %s", cameraName);
        psFree(camera);
        return NULL;
    }

    return camera;
}

psDB *pmConfigDB(pmConfig *config)
{
    PS_ASSERT_PTR_NON_NULL(config, NULL);
    PS_ASSERT_PTR_NON_NULL(config->site, NULL);

    #ifndef HAVE_PSDB

    return NULL;
    #else

    psBool mdStatus01 = false;
    psBool mdStatus02 = false;
    psBool mdStatus03 = false;
    psBool mdStatus04 = false;
    psBool mdStatus05 = false;

    // XXX leaky strings
    psString dbServer = psMetadataLookupStr(&mdStatus01, config->site, "DBSERVER");
    psString dbUsername = psMetadataLookupStr(&mdStatus02, config->site, "DBUSER");
    psString dbPassword = psMetadataLookupStr(&mdStatus03, config->site, "DBPASSWORD");
    psString dbName = psMetadataLookupStr(&mdStatus04, config->site, "DBNAME");
    psS32 dbPort = psMetadataLookupS32(&mdStatus05, config->site, "DBPORT");
    if (!mdStatus05) {
        dbPort = 0;
    }
    if (!(mdStatus01 && mdStatus02 && mdStatus03 && mdStatus04)) {
        psLogMsg("psModules.config", PS_LOG_WARN,
                 "Could not determine database server, name, user, and password from site metadata.\n");
        return NULL;
    }

    return psDBInit(dbServer, dbUsername, dbPassword, dbName, dbPort);
    #endif
}


bool pmConfigConformHeader(psMetadata *header, const psMetadata *format)
{
    PS_ASSERT_PTR_NON_NULL(header, false);
    PS_ASSERT_PTR_NON_NULL(format, false);

    bool mdok = true;                   // Status of MD lookup
    psMetadata *rules = psMetadataLookupMetadata(&mdok, format, "RULE"); // How to identify this format
    if (!mdok || !rules) {
        psError(PS_ERR_IO, true, "Unable to find RULE in camera format.\n");
        return false;
    }

    psMetadataIterator *rulesIter = psMetadataIteratorAlloc(rules, PS_LIST_HEAD, NULL); // Iterator for rules
    psMetadataItem *rulesItem = NULL;   // Item from iteration
    while ((rulesItem = psMetadataGetAndIncrement(rulesIter))) {
        psMetadataItem *newItem = psMetadataItemCopy(rulesItem); // Copy of item
        psMetadataAddItem(header, newItem, PS_LIST_TAIL, PS_META_REPLACE);
        psFree(newItem);                // Drop reference
    }
    psFree(rulesIter);

    return true;
}

psArray *pmConfigFileSets(pmConfig *config, const char *file, const char *list)
{
    PS_ASSERT_PTR_NON_NULL(config, NULL);
    PS_ASSERT_PTR_NON_NULL(config->argc, NULL);
    PS_ASSERT_INT_NONNEGATIVE(*config->argc, NULL);
    PS_ASSERT_PTR_NON_NULL(config->argv, NULL);
    PS_ASSERT_STRING_NON_EMPTY(file, NULL);
    PS_ASSERT_STRING_NON_EMPTY(list, NULL);

    int Narg;

    // we load all input files onto a psArray, to be parsed later
    psArray *input = psArrayAllocEmpty(16);

    // load the list of filenames the supplied file
    // maybe a comma-separated list of words
    // each word may be a glob: "file*.fits"
    if ((Narg = psArgumentGet (*config->argc, config->argv, file))) {

        // select the word after 'file' and split by comma
        psArgumentRemove (Narg, config->argc, config->argv);
        psArray *words = psStringSplitArray (config->argv[Narg], ",", true);
        psArgumentRemove (Narg, config->argc, config->argv);

        // parse the word as a glob
        glob_t globList;
        for (int i = 0; i < words->n; i++) {
            globList.gl_offs = 0;
            glob (words->data[i], 0, NULL, &globList);

            // if the glob does not match, save the literal word:
            // otherwise save all glob matches
            if (globList.gl_pathc == 0) {
                psArrayAdd (input, 16, words->data[i]);
            } else {
                for (int j = 0; j < globList.gl_pathc; j++) {
                    char *filename = psStringCopy (globList.gl_pathv[j]);
                    psArrayAdd (input, 16, filename);
                    psFree (filename);
                }
            }
        }
        psFree (words);
    }

    // load the list from the supplied text file
    if ((Narg = psArgumentGet (*config->argc, config->argv, list))) {
        int nItems;
        char line[1024]; // XXX limits the list lines to 1024 chars
        char word[1024];
        char *filename;

        psArgumentRemove (Narg, config->argc, config->argv);
        FILE *f = fopen (config->argv[Narg], "r");
        if (f == NULL) {
            psAbort ("psphot", "unable to open specified list file");
        }
        while (fgets (line, 1024, f) != NULL) {
            nItems = sscanf (line, "%s", word);
            switch (nItems) {
            case 0:
                break;
            case 1:
                filename = psStringCopy (word);
                psArrayAdd (input, 16, filename);
                psFree (filename);
                break;
            default:
                // rigid format, no comments allowed?
                psAbort ("pmConfig", "error parsing input list file");
                break;
            }
        }
        psArgumentRemove (Narg, config->argc, config->argv);
    }

    return input;
}

bool pmConfigFileSetsMD(psMetadata *metadata, pmConfig *config, const char *name,
                        const char *file, const char *list)
{
    PS_ASSERT_PTR_NON_NULL(metadata, false);
    PS_ASSERT_PTR_NON_NULL(config, false);
    PS_ASSERT_STRING_NON_EMPTY(name, NULL);
    PS_ASSERT_STRING_NON_EMPTY(file, NULL);
    PS_ASSERT_STRING_NON_EMPTY(list, NULL);

    psErrorClear();   // pmConfigFileSets may or may not call psError, so
    // if files->n == 0 we'll want to call psError(..., false, ...)
    psArray *files = pmConfigFileSets(config, file, list);
    if (files->n == 0) {
        // psError(PS_ERR_IO, false, "pmConfigFileSets failed to find %s in the argument list", name);
        psFree (files);
        return false;
    }

    psMetadataAddPtr(metadata, PS_LIST_TAIL, name,  PS_DATA_ARRAY, "", files);
    psFree (files);
    return true;
}

// convert the supplied name, create a new output psString
psString pmConfigConvertFilename(const char *filename, const pmConfig *config, bool create)
{
    PS_ASSERT_STRING_NON_EMPTY(filename, NULL);
    PS_ASSERT_PTR_NON_NULL(config, NULL);

    // strip file:// from front of name
    if (!strncasecmp(filename, "file:", strlen("file:"))) {
        psString newName = psStringCopy(filename);

        char *point = newName + strlen("file:");
        while (*point == '/')
            point ++;
        char *tmpName = NULL;
        psStringAppend (&tmpName, "/%s", point);
        psFree (newName);
        newName = tmpName;

        // open the to create it if it doesn't exist.  This could cause a
        // strange looking error if we can't access the file.
        // XXX perhaps we should try access() first? -JH
        int fd = open(newName, O_RDONLY|O_CREAT);
        if (fd < 0) {
            psError(PS_ERR_IO, true, "unable to open() file %s", newName);
            psFree(newName);
            return NULL;
        }
        if (close(fd) < 0) {
            psError(PS_ERR_IO, true, "unable to open() file %s", newName);
            psFree(newName);
            return NULL;
        }

        return newName;
    }

    // replace path://PATH with matched datapath
    if (!strncasecmp(filename, "path://", strlen("path://"))) {
        PS_ASSERT_METADATA_NON_NULL(config->site, NULL);

        psString newName = psStringCopy(filename);

        // filename should be of the form: path://PATH/rest/of/file
        // replace PATH with matching name from config->site:DATAPATH
        psMetadata *datapath = psMetadataLookupPtr (NULL, config->site, "DATAPATH");
        if (datapath == NULL) {
            psError(PS_ERR_UNKNOWN, true, "DATAPATH is not defined in config.site");
            psFree (newName);
            return NULL;
        }

        char *point = newName + strlen("path://");
        char *mark = strchr (point, '/');
        if (mark == NULL) {
            psError(PS_ERR_UNKNOWN, true, "syntax error in PATH-style name %s", newName);
            psFree (newName);
            return false;
        }

        psString path = psStringNCopy (point, mark - point);
        char *realpath = psMetadataLookupStr (NULL, datapath, path);
        if (realpath == NULL) {
            psError(PS_ERR_UNKNOWN, true,
                    "path (%s) not defined in config.site:DATAPATH for PATH-style name %s",
                    path, newName);
            psFree(newName);
            psFree(path);
            return false;
        }
        psFree(path);

        char *tmpName = NULL;
        psStringAppend(&tmpName, "%s/%s", realpath, mark + 1);
        psFree(newName);
        newName = tmpName;

        // open the to create it if it doesn't exist.  This could cause a
        // strange looking error if we can't access the file.
        // XXX perhaps we should try access() first? -JH
        int fd = open(newName, O_RDONLY|O_CREAT);
        if (fd < 0) {
            psError(PS_ERR_IO, true, "unable to open() file %s", newName);
            psFree(newName);
            return NULL;
        }
        if (close(fd) < 0) {
            psError(PS_ERR_IO, true, "unable to open() file %s", newName);
            psFree(newName);
            return NULL;
        }

        return newName;
    }

    // substitute neb://name with matched nebulous name
    if (!strncasecmp(filename, "neb://", strlen("neb://"))) {
        #ifdef HAVE_NEBCLIENT

        bool status = false;
        psString nebulous_server = psMetadataLookupStr(&status, config->site, "NEBULOUS_SERVER");
        if (!status) {
            psError(PM_ERR_CONFIG, true, "failed to lookup config value for NEBULOUS_SERVER.");
            return NULL;
        }
        if (!nebulous_server) {
            psError(PM_ERR_CONFIG, true, "Could not determine nebulous server URI.");
            return NULL;
        }

        nebServer *server = nebServerAlloc(nebulous_server);
        if (!server) {
            psError(PM_ERR_SYS, true, "failed to create a nebServer object: %s", nebErr(server));
            nebServerFree(server);
            return NULL;
        }

        // ignore the leading neb://
        char *cleanFilename = (char *)filename + strlen("neb://");

        char *nebfile = NULL;
        if (create) {
            nebfile = nebCreate(server, cleanFilename, 0, NULL, NULL, NULL);
            if (!nebfile) {
                psError(PM_ERR_SYS, true, "failed to create a new nebulous key: %s", nebErr(server));
                nebServerFree(server);
                return NULL;
            }
        } else {
            nebfile = nebFind(server, cleanFilename);
            if (!nebfile) {
                psError(PM_ERR_SYS, true, "failed to find nebulous key: %s", nebErr(server));
                nebServerFree(server);
                return NULL;
            }
        }

        // convert nebfile into a psString
        psString path = psStringCopy(nebfile);
        psFree(nebfile);
        nebServerFree(server);

        return path;

        #else // ifdef HAVE_NEBCLIENT

        psError(PM_ERR_PROG, true, "psModules was compiled without nebulous support.");
        return NULL;
        #endif // ifdef HAVE_NEBCLIENT

    }

    // if we go this far, do nothing
    return psStringCopy(filename);
}
