/* nwc_os_makedirs.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2017 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 "nwc_os_makedirs.hh"
#include "aguix/lowlevelfunc.h"
#include "aguix/util.h"
#include "nwc_fsentry.hh"
#include "nwc_path.hh"

namespace NWC {
    namespace OS {
        int prepare_deep_dir_info( const std::string &base_dir,
                                   const std::string &sub_segments,
                                   std::vector< deep_dir_info > &segments )
        {
            int res = 0;
            std::vector< std::string > path_components;
            std::string path = base_dir;

            segments.clear();

            AGUIXUtils::split_string( path_components, sub_segments, '/' );

            for ( auto &segment : path_components ) {
                if ( segment.empty() ) continue;

                path = NWC::Path::join( path, segment );

                NWC::FSEntry fe( path );

                if ( ! fe.entryExists() ||
                     ! fe.isDir( true ) ) {
                    res = -EINVAL;
                    break;
                }

                mode_t mode;
                uid_t user;
                gid_t group;

                if ( fe.isLink() ) {
                    mode = fe.stat_dest_mode();
                    user = fe.stat_dest_userid();
                    group = fe.stat_dest_groupid();
                } else {
                    mode = fe.stat_mode();
                    user = fe.stat_userid();
                    group = fe.stat_groupid();
                }

                deep_dir_info ddi( segment,
                                   mode,
                                   user,
                                   group );
                
                segments.push_back( ddi );
            }

            return res;
        }

        int make_dirs( const std::string &base_dir,
                       std::vector< deep_dir_info > &segments,
                       bool post_run )
        {
            std::string path = base_dir;
            int res = 0;

            for ( auto &s : segments ) {
                if ( s.get_segment_name().empty() ) continue;

                path = NWC::Path::join( path, s.get_segment_name() );

                if ( post_run ) {
                    if ( s.was_created() ) {
                        // need to apply correct permissions
                        worker_chown( path.c_str(),
                                      s.get_user(),
                                      s.get_group() );
                        worker_chmod( path.c_str(), s.get_mode() );
                    }
                } else {
                    NWC::FSEntry fe( path );

                    if ( fe.entryExists() ) {
                        if ( fe.isDir( true ) ) {
                            continue;
                        }

                        res = -EEXIST;
                        break;
                    }

                    res = worker_mkdir( path.c_str(), 0700 );
                    if ( res != 0 ) {
                        break;
                    }
                    s.set_was_created( true );
                }
            }

            return res;
        }

        int make_dirs( const std::string &dirname )
        {
            NWC::FSEntry fse( dirname );

            if ( fse.entryExists() ) {
                if ( fse.isDir( true ) ) {
                    // nothing to do
                    return 0;
                }

                return -EEXIST;
            }

            std::string parent_dirname = fse.getDirname();

            if ( parent_dirname != "" &&
                 parent_dirname != "." &&
                 parent_dirname != "/" ) {
                int res = make_dirs( parent_dirname );

                if ( res != 0 ) {
                    return res;
                }
            }

            int res = worker_mkdir( dirname.c_str(), 0700 );

            return res;
        }

    }
}
