#!/usr/bin/env python

# This file is part of Window-Switch.
# Copyright (c) 2009-2013 Antoine Martin <antoine@nagafix.co.uk>
# Window-Switch is released under the terms of the GNU GPL v3

import os

from winswitch.util.process_util import exec_nopipe
from winswitch.util.file_io import get_server_dir
from winswitch.objects.mount_point import MountPoint
from winswitch.net.net_util import is_localhost
from winswitch.fs.fs_client_helper import FS_Client_Helper
from winswitch.globals import WIN32


class Samba_Client_Helper(FS_Client_Helper):
	"""
	SMB fs support.
	"""

	def __init__ (self, config):
		FS_Client_Helper.__init__(self, MountPoint.SMB, config.mount_location, config.smbmount_command, config.smbumount_command)


	def do_mount(self, user, mp):
		if WIN32:
			self.do_winapi_mount(user, mp)
		else:
			self.do_unix_mount(user, mp)

	def do_winapi_mount(self, user, mp):
		self.serror("Not implemeted yet!", user, mp)
		return False

	def do_unix_mount(self, user, mp):
		mnt_path = self.get_local_mount_point(user.host, mp.path)
		self.sdebug("mount path=%s" % mnt_path, user, mp)
		cmd = self.mount_command.split(" ")
		if is_localhost(mp.host):
			host = user.local_samba_host
		else:
			host = mp.host
		cmd += ["\\\\%s\\%s" % (host, mp.path), mnt_path, "-o", "port=%s" % user.local_samba_port]
		filename = None
		try:
			if mp.auth_mode and mp.password:
				import tempfile
				(credentials, filename) = tempfile.mkstemp(prefix="credentials", dir=get_server_dir())
				data = "username=%s\n" % mp.username
				data += "password=%s\n" % mp.password
				cred_file = os.fdopen(credentials, 'w')
				cred_file.write(data)
				cred_file.close()
				cmd += ["-o", "credentials=%s" % filename]
			else:
				cmd += ["-o", "guest"]

			proc = exec_nopipe(cmd, wait=True)
		finally:
			if filename:
				os.unlink(filename)
		self.slog("exec(%s)=%s" % (cmd, proc), user, mp)
		if proc and proc.returncode==0:
			mp.mount_point = mnt_path
			return True
		else:
			return False
