/* getfsentmounttable.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2009,2012 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 "getfsentmounttable.hh"
#include "mounttable_entry.hh"
#include "nwc_fsentry.hh"
#ifdef HAVE_GETFSENT
#include <fstab.h>
#endif

#ifdef HAVE_GETFSENT
typedef std::pair< mode_t, dev_t > w_osdevice_t;

static w_osdevice_t getOSDevice( const std::string &dev )
{
    NWC::FSEntry fe( dev );

    if ( ! fe.entryExists() ) {
        return std::make_pair( 0, 0 );
    }

    if ( fe.isLink() ) {
        return std::make_pair( fe.stat_dest_mode(),
                               fe.stat_dest_rdev() );
    } else {
        return std::make_pair( fe.stat_mode(),
                               fe.stat_rdev() );
    }
}
#endif

GetFsEntMountTable::GetFsEntMountTable( const std::string &file ) : GetMntEntMountTable( file )
{
}

std::list<MountTableEntry> GetFsEntMountTable::readEntries()
{
    std::list<MountTableEntry> l;

#ifdef HAVE_GETFSENT
    if ( setfsent() == 1 ) {
	struct fstab *fstab_entry;
        
        while ( true ) {
            fstab_entry = getfsent();
            if ( ! fstab_entry ) break;

            if ( fstab_entry->fs_spec != NULL &&
                 fstab_entry->fs_file ) {
                MountTableEntry mte( fstab_entry->fs_spec );
                mte.setMountPoint( fstab_entry->fs_file );
            
                w_osdevice_t stat1 = getOSDevice( fstab_entry->fs_spec );
                if ( stat1.first && stat1.second ) {
                    mte.setMode( stat1.first );
                    mte.setRDev( stat1.second );
                }
            
                l.push_back( mte );
            }            
	}

        endfsent();
    }
#endif
    return l;
}
