//
// LDASTools AL - A library collection to provide an abstraction layer
//
// Copyright (C) 2018 California Institute of Technology
//
// LDASTools AL is free software; you may redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 (GPLv2) of the
// License or at your discretion, any later version.
//
// LDASTools AL is distributed in the hope that it will be useful, but
// without any warranty or even the implied warranty of merchantability
// or fitness for a particular purpose. See the GNU General Public
// License (GPLv2) for more details.
//
// Neither the names of the California Institute of Technology (Caltech),
// The Massachusetts Institute of Technology (M.I.T), The Laser
// Interferometer Gravitational-Wave Observatory (LIGO), nor the names
// of its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// You should have received a copy of the licensing terms for this
// software included in the file LICENSE located in the top-level
// directory of this package. If you did not, you can view a copy at
// http://dcc.ligo.org/M1500244/LICENSE
//

#include "ldastoolsal/MkDir.hh"

extern "C" {
#include <sys/stat.h>
#include <unistd.h>
} // extern "C"

#include <cerrno>
#include <sstream>
#include <stdexcept>

#ifndef ENOERR
#define ENOERR 0
#endif /* ENOERR */

namespace
{
    const char*
    failure( int Error )
    {
        switch ( Error )
        {
        case EACCES:
            return "Insufficient permission";
        default:
            break;
        }
        return "Unspecified system error";
    }
} // namespace

namespace LDASTools
{
    namespace Cmd
    {
        const char MkDir::PATH_SEP = '/';

        MkDir ::MkDir( mode_type Mode, option_type /* Options */ )
            : mode( Mode )
        {
        } // MkDir::MkDir

        void
        MkDir::operator( )( const std::string& Directory ) const
        {
            errno = ENOERR;

            eval( Directory );

            if ( errno != ENOERR )
            {
                std::ostringstream msg;

                msg << "Failed to create directory: " << Directory << " ("
                    << failure( errno ) << ")";

                throw std::runtime_error( msg.str( ) );
            }
        } // MkDir::operator

        void
        MkDir::eval( const std::string& Directory ) const
        {
            errno = ENOERR;

            if ( ::mkdir( Directory.c_str( ), mode ) != 0 )
            {
                if ( errno == EEXIST )
                {
                    //-------------------------------------------------------------
                    // Stop because the directory alread exists.
                    // Do not consider this a error.
                    //-------------------------------------------------------------
                    errno = ENOERR;
                    return;
                }
                if ( ( errno == ENOENT ) &&
                     ( mode | OPT_MAKE_PARENT_DIRECTORIES ) )
                {
                    //-------------------------------------------------------------
                    // Recursive call to try to create the parent
                    //-------------------------------------------------------------
                    size_t pos = Directory.rfind( PATH_SEP );

                    if ( ( pos != std::string::npos ) && ( pos > 1 ) )
                    {
                        this->operator( )( Directory.substr( 0, pos ) );
                        if ( ( errno == ENOENT ) || ( errno == ENOERR ) )
                        {
                            ::mkdir( Directory.c_str( ), mode );
                        } // if - errno
                    } // if - pos
                } // if - errno
            } // if - mkdir

        } // MkDir::eval
    } // namespace Cmd
} // namespace LDASTools
