#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <qmessagebox.h>
#include <kapp.h>
#include <iostream.h>

#if HAVE_SYS_VFSTAB_H
#include <sys/vfstab.h>
#include <sys/mnttab.h>
#else
//#include <fstab.h>
#include <mntent.h>
#endif

#include "protocol.h"
#include "mountprot.h"

MountProtocol::MountProtocol(const char *device, const char *mpoint, const char *fstype)
	: FileProtocol(mpoint)
{
	Device = device;
	FSType = fstype;
	MountPoint = mpoint;
	Type = Protocol::Mount;
	if (MountPoint.isEmpty()) {
		if (getMountPoint()) {
			Mountable = TRUE;
			Prefix = "file:";
			Prefix += MountPoint;
			if (Prefix[Prefix.length()-1] != '/') Prefix += "/";
		}
		else {
			Mountable = FALSE;
			Prefix = "";
		}
	}
}


bool MountProtocol::isMounted()
{
#if HAVE_SYS_VFSTAB_H
	FILE	*fp = fopen(MNTTAB,"r");
	if (fp == 0) return FALSE;
	int	val;
	struct mnttab	buf, spec;
	mntnull(&spec);
	spec.mnt_special = Device.data();
	if (!MountPoint.isEmpty()) spec.mnt_mountp = MountPoint.data();
	if (!FSType.isEmpty()) spec.mnt_fstype = FSType.data();
	val = getmntany(fp,&buf,&spec);
	fclose(fp);
	return (val == 0);
#else
	FILE	*fp = setmntent(MOUNTED,"r");
	if (fp == 0) return FALSE;
	struct mntent	*buf;
	bool	done(FALSE);
	while (!done && (buf = getmntent(fp)) != 0) {
		if (buf->mnt_fsname == Device) done = TRUE;
		if (!MountPoint.isEmpty() && MountPoint != buf->mnt_dir) done = FALSE;
		if (!FSType.isEmpty() && FSType != buf->mnt_type) done = FALSE;
	}
	endmntent(fp);
	return done;
#endif
}

bool MountProtocol::getMountPoint()
{
#if HAVE_SYS_VFSTAB_H
	FILE	*fp = fopen(VFSTAB,"r");
	if (fp == 0) return FALSE;
	struct vfstab	buf;
	int	val = getvfsspec(fp,&buf,Device.data());
	fclose(fp);
	if (val == 0) MountPoint = buf.vfs_mountp;
	return (val == 0);
#else
	FILE	*fp = setmntent(MNTTAB,"r");
	if (fp == 0) return FALSE;
	struct mntent	*buf;
	bool	done(FALSE);
	while (!done && (buf = getmntent(fp)) != 0) {
		if (Device == buf->mnt_fsname) done = TRUE;
	}
	if (done) MountPoint = buf->mnt_dir;
	endmntent(fp);
	return done;
#endif
}

bool MountProtocol::mount()
{
	QString		cmd("mount");
	if (!FSType.isEmpty()) { cmd += " -t "; cmd += FSType.data();}
	cmd += (" " + Device);
	if (!MountPoint.isEmpty()) cmd += (" " + MountPoint);
	if (system(cmd.data()) != 0) return FALSE;
	return TRUE;
}

bool MountProtocol::umount()
{
	QString		cmd("umount ");
	cmd += Device;
	if (system(cmd.data()) != 0) return FALSE;
	return TRUE;
}

bool MountProtocol::finish()
{
	if (isMounted()) {
		QString		msg(Device.data());
		msg += i18n(" is mounted : unmount ?");
		if (QMessageBox::information((QWidget*)0,i18n("Confirmation"),msg.data(),QMessageBox::Ok | QMessageBox::Default,QMessageBox::Cancel | QMessageBox::Escape) == QMessageBox::Ok)
			if (!umount()) QMessageBox::critical((QWidget*)0,i18n("Error"),i18n("Unable to unmount device"),QMessageBox::Ok | QMessageBox::Default,0);
	}
	return TRUE;
}
