/* workerinitialsettings.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2010-2021 Ralf Hoffmann.
 * You can contact me at: ralf@boomerangsworld.de
 *   or http://www.boomerangsworld.de/worker
 *
 * This program is free software; you can 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 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "workerinitialsettings.hh"
#include "nwc_path.hh"
#include "nwc_fsentry.hh"

WorkerInitialSettings *WorkerInitialSettings::m_instance = NULL;

WorkerInitialSettings::WorkerInitialSettings()
{
    char *homestr;
    
    homestr = getenv( "HOME" );
    if ( homestr ) {
        m_config_base_dir = NWC::Path::join( homestr, ".worker" );
    } else {
        fprintf( stderr, "Worker: There is no HOME variable defined, please set it to your home directory!\n" );
        fprintf( stderr, "Worker: Cannot continue!\n" );
        // this is a very unusual situation and because I don't know where to store the information
        // in this case I will quit here
        exit ( 20 );
    }

    // be backward compatible, accept $HOME/.worker dir
    if ( NWC::FSEntry( m_config_base_dir ).entryExists() ) {
        return;
    }

    char *xdg_home = getenv( "XDG_CONFIG_HOME" );
    if ( xdg_home && strlen( xdg_home ) > 0 ) {
        m_config_base_dir = NWC::Path::join( xdg_home, "worker" );
    } else {
        std::string xdg_config_dir = NWC::Path::join( homestr, ".config" );

        if ( NWC::FSEntry( xdg_config_dir ).entryExists() ) {
            m_config_base_dir = NWC::Path::join( xdg_config_dir, "worker" );
        }
    }
}

WorkerInitialSettings::~WorkerInitialSettings()
{
}
    
WorkerInitialSettings &WorkerInitialSettings::getInstance()
{
    if ( ! m_instance ) {
        m_instance = new WorkerInitialSettings();
    }
    
    return *m_instance;
}

void WorkerInitialSettings::setConfigBaseDir( const std::string &dir )
{
    if ( NWC::Path::isAbs( dir ) ) {
        m_config_base_dir = dir;
    }
}

std::string WorkerInitialSettings::getConfigBaseDir() const
{
    return m_config_base_dir;
}

void WorkerInitialSettings::destroyInstance()
{
    delete m_instance;
    m_instance = NULL;
}
