/***************************************************************************
    smb4kmounter.h  -  The core class that mounts the shares.
                             -------------------
    begin                : Die Jun 10 2003
    copyright            : (C) 2003-2007 by Alexander Reinholdt
    email                : dustpuppy@users.berlios.de
 ***************************************************************************/

/***************************************************************************
 *   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., 59 Temple Place, Suite 330, Boston,   *
 *   MA  02111-1307 USA                                                    *
 ***************************************************************************/

#ifndef SMB4KMOUNTER_H
#define SMB4KMOUNTER_H

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

// Qt includes
#include <qobject.h>
#include <qstringlist.h>
#include <qptrqueue.h>
#include <qfile.h>

// KDE includes
#include <kprocess.h>

// application specific includes
#include "smb4kdefs.h"

// forward declarations
class Smb4KMounterPrivate;
class Smb4KShare;


/**
 * This is one of the core classes of Smb4K. It manages the mounting
 * and unmounting of remote Samba/Windows shares. Additionally it maintains a
 * list of all mounts with SMBFS and CIFS file system that are present
 * on the system.
 *
 * @author Alexander Reinholdt <dustpuppy@users.berlios.de>
 */

class Smb4KMounter : public QObject
{
  Q_OBJECT

  public:
    /**
     * The constructor.
     */
    Smb4KMounter( QObject *parent = 0, const char *name = 0 );
    /**
     * The destructor.
     */
    ~Smb4KMounter();

    /**
     * Aborts a running process.
     */
    void abort();

    /**
     * Enumeration for the state of the process. The members are also
     * used in the results() signal as return values.
     */
    enum State{ Remount, Import, Mount, Unmount, UnmountAll, Idle };

    /**
     * Unmounts a share. This can either be done the "normal" way, or you may
     * force it. If you decide the force the unmounting by setting @p force to TRUE,
     * a lazy unmount will be initiated. With the parameter @p noMessage you can
     * suppress any error messages.
     *
     * @param share       The share object that should be unmounted.
     *
     * @param force       Force the unmounting of the share.
     *
     * @param noMessage   Determines whether this function should emit an error code in case of an error.
     *                    The default value is FALSE.
     */
    void unmountShare( Smb4KShare *share, bool force = false, bool noMessage = false );

    /**
     * Unmounts all shares at once.
     */
    void unmountAllShares();

    /**
     * Mounts a share.
     *
     * @param workgroup   The workgroup of the share.
     *
     * @param host        The server where the share is located.
     *
     * @param ip          The IP address of the host.
     *
     * @param share       The name of the share.
     */
    void mountShare( const QString &workgroup, const QString &host, const QString &ip, const QString &share );

    /**
     * Returns the unsorted list of mounted shares.
     */
    const QValueList<Smb4KShare *> &getShares() { return m_mounted_shares; };

    /**
     * Find a share in the list with its path.
     */
    Smb4KShare* findShareByPath( const QString &path );

    /**
     * Find all mounts of the particular share @p share on the system.
     *
     * @param name        The name of the share
     *
     * @returns the complete list of mounts of @p share.
     */
    QValueList<Smb4KShare> findShareByName( const QString &name );

    /**
     * This function returns TRUE if a share is mounted and FALSE otherwise.
     *
     * @param name        The name of the share. It has to look like this:
     *                    //HOST/SHARE.
     *
     * @param userOnly    Specifies whether this function should only consider
     *                    shares mounted by the user or all shares that are
     *                    available on the system. The default is TRUE.
     *
     * @return TRUE if the share is mounted and FALSE otherwise.
     */
    bool isMounted( const QString &name, bool userOnly = true );

    /**
     * This function reports if the mounter is running or not.
     *
     * @returns             TRUE if the scanner is running and FALSE otherwise.
     */
    bool isRunning() { return m_working; }

    /**
     * This function returns the list of broken shares.
     *
     * @returns             The list of broken shares.
     */
    const QValueList<Smb4KShare *> getBrokenShares();

    /**
     * This function executes Smb4KMounter::slotShutdown(). Under normal circumstances,
     * there is no need to use this function, because everything that is done here is
     * also done when KApplication::shutDown() is emitted. However, it comes in handy
     * when you need to perform last actions in a plugin.
     */
    void prepareForShutdown();

    /**
     * This function initializes import of mounted shares and the remounting of recently
     * used shares.
     */
    void init();

  signals:
    /**
     * This signal emits the run state.
     *
     * @param state           The so-called run state. There are several defined
     *                        in the smb4kdefs.h header file.
     */
    void state( int state );

    /**
     * Tells the program, that the shares list has been updated.
     */
    void updated();

    /**
     * This signal is emitted when a share has successfully been mounted or
     * if it has already been mounted.
     *
     * @param mountpoint      The mount point of the share.
     */
    void mountedShare( const QString &mountpoint );

    /**
     * This signal is emitted just before a share is unmounted.
     *
     * @param mountpoint       The mount point of the share that is going to
     *                         be unmounted.
     */
    void aboutToUnmount( const QString &mountpoint );

  protected:
    /**
     * Starts a process. It takes an interger, that determines,
     * which process has to be started.
     */
    void startProcess( int state );

    /**
     * Is called, when the process ended.
     */
    void endProcess();

    /**
     * Finishes the mounting of shares.
     */
    void processMount();

    /**
     * Finishes the unmounting of a single share.
     */
    void processUnmount();

    /**
     * Reimplemented from QObject
     */
    void timerEvent( QTimerEvent *e );

  protected slots:
    /**
     * Is called, when the process exits.
     */
    void slotProcessExited( KProcess * );

    /**
     * Is called, if output is received on Stdout.
     */
    void slotReceivedStdout( KProcess *, char *buf, int len );

    /**
     * Is called, if output is received on Stderr.
     */
    void slotReceivedStderr( KProcess *, char *buf, int len );

    /**
     * This slot is called by the KApplication::shutDown() signal.
     * Is does everything that has to be done before the program
     * really exits.
     */
    void slotShutdown();

  private:
    /**
     * Remount shares that were used in the last session.
     */
    void remount();

    /**
     * Imports mounted shares.
     */
    void import();

    /**
     * Mounts a selected share.
     */
    void mount( const QString &workgroup, const QString &host, const QString &ip, const QString &share );

    /**
     * Unmounts the selected item.
     */
    void unmount( const QString &mountpoint, bool noMessage, bool force = false );

    /**
     * Unmounts all shares at once.
     */
    void unmountAll();

    /**
     * Checks if the share @p share is accessible or not and sets Smb4KShare::isBroken()
     * accordingly. Additionally, Smb4KShare::totalDiskSpace() and Smb4KShare::freeDiskSpace()
     * are set to the current values.
     *
     * @param share           The share that should be checked.
     */
    void checkAccessibility( Smb4KShare *share );

    /**
     * The KProcess object.
     */
    KProcess *m_proc;

    /**
     * The buffer.
     */
    QString m_buffer;

    /**
     * The queue, where the incoming requests are stored.
     */
    QPtrQueue<QString> m_queue;

    /**
     * Determines, whether the mounter is running or not.
     */
    bool m_working;

    /**
     * Holds the list of currently mounted shares as a pointer list.
     */
    QValueList<Smb4KShare *> m_mounted_shares;

    /**
     * Makes sure that the error message concerning the missing of
     * the file /proc/mounts is only shown once.
     */
    bool m_proc_error;

    /**
     * The internal state of the process. Do not mix this up with
     * the state that's emitted to notify the application about changes.
     */
    int m_state;

#ifndef __FreeBSD__
    /**
     * This file object points to /proc/mounts.
     */
    QFile m_proc_mounts;
#endif

    /**
     * This is the pointer to the private helper class.
     */
    Smb4KMounterPrivate *m_priv;
};

#endif
