/***************************** 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 <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

MvTmpFile::MvTmpFile(bool autoRemove) : autoRemove_(autoRemove)
{
    static char name[1024];
    char *p;
    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);

    close(creat(name,0777));
    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);
}
