/* getmntinfomounttable.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 "getmntinfomounttable.hh"
#include "mounttable_entry.hh"
#include "nwc_fsentry.hh"
#ifdef HAVE_GETMNTINFO_FBSD
#include <sys/param.h>
#include <sys/ucred.h>
#include <sys/mount.h>
#endif

#ifdef HAVE_GETMNTINFO_NBSD
#include <sys/types.h>
#include <sys/statvfs.h>
#endif

#if defined( HAVE_GETMNTINFO_FBSD ) || defined( HAVE_GETMNTINFO_NBSD )
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

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

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

#if defined( HAVE_GETMNTINFO_FBSD ) || defined( HAVE_GETMNTINFO_NBSD )

#if defined( HAVE_GETMNTINFO_FBSD )
    struct statfs *mount_entries;
#elif defined( HAVE_GETMNTINFO_NBSD )
    struct statvfs *mount_entries;
#endif
    int n = 0;

#if defined( HAVE_GETMNTINFO_FBSD )
    n = getmntinfo( &mount_entries, MNT_NOWAIT );
#elif defined( HAVE_GETMNTINFO_NBSD )
    n = getmntinfo( &mount_entries, ST_NOWAIT );
#endif
    for ( int i = 0; i < n; i++ ) {
        if ( mount_entries[i].f_mntfromname != NULL &&
             mount_entries[i].f_mntonname != NULL ) {
            MountTableEntry mte( mount_entries[i].f_mntfromname );
            mte.setMountPoint( mount_entries[i].f_mntonname );
        
            w_osdevice_t stat1 = getOSDevice( mount_entries[i].f_mntfromname );
            if ( stat1.first && stat1.second ) {
                mte.setMode( stat1.first );
                mte.setRDev( stat1.second );
            }
        
            l.push_back( mte );
        }
    }
#endif
    return l;
}
