/* avfssupport.cc
 * This file belongs to Worker, a filemanager for UNIX/X11.
 * Copyright (C) 2007 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 "avfssupport.hh"
#include <algorithm>

static std::string find_next_vfs_handler( std::string &searchstr, std::string::size_type &pos )
{
  std::string res = "";
  std::string::size_type pos2;

  pos = searchstr.find_first_of( "0123456789", pos );
  if ( pos != std::string::npos ) {
    pos = searchstr.find_first_of( " \t", pos );
    if ( pos != std::string::npos ) {
      pos = searchstr.find_first_not_of( " \t", pos );
      if ( pos != std::string::npos ) {
	pos2 = searchstr.find( ":", pos );
	if ( pos2 != std::string::npos )
	  res.assign( searchstr, pos, pos2 - pos );
      }
    }
  }
  if ( pos != std::string::npos ) {
    pos = searchstr.find( "\n", pos );
  }
  return res;
}

std::vector<std::string> AVFSSupport::getAVFSModules()
{
  int fd, l;
  std::string::size_type pos;
  std::string a1, a2;
  std::vector<std::string> v;
  char buf[128];
  
  a1 = "";
  fd = worker_open( "/#avfsstat/modules", O_RDONLY, 0 );
  if ( fd >= 0 ) {
    for (;;) {
      l = worker_read( fd, buf, sizeof( buf ) );
      if ( l > 0 ) {
	a1.append( buf, l );
      } else break;
    }
    worker_close( fd );
  }

  pos = 0;
  for (;;) {
    a2 = find_next_vfs_handler( a1, pos );
    if ( a2.length() < 1 ) break;
    v.push_back( a2 );
  }
  std::sort( v.begin(), v.end() );

  return v;
}
