/***************************** LICENSE START ***********************************

 Copyright 2014 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "MvTmpFile.h"
#include "MvWindef.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstdio>
#include <cstring>
#include <cstdlib>

#ifndef METVIEW_ON_WINDOWS
#include <unistd.h>
#else
#include <io.h>
#define R_OK 04
#endif

MvTmpFile::MvTmpFile(bool autoRemove) :
    autoRemove_(autoRemove)
{
    static char name[1024];
    char* p = nullptr;
    std::string tmpDir;
    static char* tmpDirCh = getenv("TMPDIR");
    tmpDir = std::string((tmpDirCh) ? tmpDirCh : "");

#ifdef ECCODES_UI
    p = tempnam(tmpDir.c_str(), "cdui_");
#else
    p = tempnam(tmpDir.c_str(), "metv_");
#endif

    strcpy(name, p);
    free(p);

#ifndef METVIEW_ON_WINDOWS
    close(creat(name, S_IRWXU | S_IRWXG | S_IRWXO));
#else
    close(creat(name, _S_IREAD | _S_IWRITE));
#endif

    path_ = std::string(name);
}

MvTmpFile::~MvTmpFile()
{
    // TODO: add further/better checks
    if (autoRemove_ &&
        exists() && !path_.empty() && path_ != "/" && path_.size() > 4) {
        unlink(path_.c_str());
    }
}

bool MvTmpFile::exists() const
{
    if (path_.empty())
        return false;
    return (access(path_.c_str(), R_OK) == 0);
}
