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

#include <stdio.h>
#include <pslib.h>

#include "ppMops.h"
#include "ppMopsVersionDefinitions.h"

#ifndef PPMOPS_VERSION
#error "PPMOPS_VERSION is not set"
#endif
#ifndef PPMOPS_BRANCH
#error "PPMOPS_BRANCH is not set"
#endif
#ifndef PPMOPS_SOURCE
#error "PPMOPS_SOURCE is not set"
#endif

psString ppMopsVersion(void)
{
    char *value = NULL;
    psStringAppend(&value, "%s@%s", PPMOPS_BRANCH, PPMOPS_VERSION);
    return value;
}

psString ppMopsSource(void)
{
    return psStringCopy(PPMOPS_SOURCE);
}

psString ppMopsVersionLong(void)
{
    psString version = ppMopsVersion();  // Version, to return
    psString source = ppMopsSource();    // Source

    psStringPrepend(&version, "ppMops ");
    psStringAppend(&version, " from %s, built %s, %s", source, __DATE__, __TIME__);
    psFree(source);

#ifdef __OPTIMIZE__
    psStringAppend(&version, " optimised");
#else
    psStringAppend(&version, " unoptimised");
#endif

    return version;
};


bool ppMopsVersionHeader(psMetadata *header)
{
    PS_ASSERT_METADATA_NON_NULL(header, false);

    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
    psString timeString = psTimeToISO(time); // The time in an ISO string
    psFree(time);
    psString history = NULL;               // History string
    psStringAppend(&history, "ppMops at %s", timeString);
    psFree(timeString);
    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, history);
    psFree(history);

    psLibVersionHeader(header);

    psString version = ppMopsVersion(); // Software version
    psString source  = ppMopsSource();  // Software source

    psStringPrepend(&version, "ppMops version: ");
    psStringPrepend(&source, "ppMops source: ");

    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, version);
    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, source);

    psFree(version);
    psFree(source);

    return true;
}

void ppMopsVersionPrint(void)
{
    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
    psString timeString = psTimeToISO(time); // The time in an ISO string
    psFree(time);
    psLogMsg("ppMops", PS_LOG_INFO, "ppMops at %s", timeString);
    psFree(timeString);

    psString pslib = psLibVersionLong();// psLib version
    psString ppMops = ppMopsVersionLong(); // ppMops version

    psLogMsg("ppMops", PS_LOG_INFO, "%s", pslib);
    psLogMsg("ppMops", PS_LOG_INFO, "%s", ppMops);

    psFree(pslib);
    psFree(ppMops);

    return;
}
