#
#  $Id: Application.py,v 1.6 1999/12/16 10:00:32 rob Exp $
#
#  Copyright 1999 Rob Tillotson <robt@debian.org>
#  All Rights Reserved
#
#  Permission to use, copy, modify, and distribute this software and
#  its documentation for any purpose and without fee or royalty is
#  hereby granted, provided that the above copyright notice appear in
#  all copies and that both the copyright notice and this permission
#  notice appear in supporting documentation or portions thereof,
#  including modifications, that you you make.
#
#  THE AUTHOR ROB TILLOTSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
#  THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
#  AND FITNESS.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
#  SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
#  RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
#  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
#  CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE!
#
"""Pyrite Application Subclass
"""

__version__ = '$Id: Application.py,v 1.6 1999/12/16 10:00:32 rob Exp $'

__copyright__ = 'Copyright 1999 Rob Tillotson <robt@debian.org>'

from types import ClassType
from whrandom import randint
import os, operator, string, time
import urlparse, urllib
if 'user' not in urlparse.uses_netloc: urlparse.uses_netloc.append('user')

from Pyrite import Plugin
from Pyrite.Store import Directory

import Sulfur
from Sulfur import Registry, Options, AppContext
from Sulfur import misc
import Sulfur.Application

import Pyrite
from Pyrite import protect_name, unprotect_name, Database, _

#
try:
    import cPickle
    pickle = cPickle
except:
    import pickle
#

def _mkdir(d):
    if os.path.exists(d):
	if not os.path.isdir(d):
	    raise RuntimeError, _("%s exists, but is not a directory") % d
    else:
	os.mkdir(d)

#def find_user_directory(dd, u, id=None):
#    if id:
#	d = os.path.join(dd, protect_name('%s.%s' % (u, id)))
#	try:
#	    os.stat(d)
#	    return d
#	except os.error:
#	    pass
#
#    d = os.path.join(dd, protect_name(u))
#    try:
#	os.stat(d)
#	return d
#    except os.error:
#	return None

#def user_directory_name(data_directory, user, uid=None):
#    if uid is not None:
#	d = os.path.join(data_directory, protect_name('%s.%s' % (user, uid)))
#    else:
#	d = os.path.join(data_directory, protect_name(str(user)))
#    return d
    

class Application(Sulfur.Application.Application):
    """A Pyrite application.
    """
    type = 'PyriteApplication'
    name = 'DefaultApplication'
    app_prefix = 'Pyrite'
    
    options = [
	Options.Boolean('old-pdb', 0, _("use old prc/pdb access code"), None,
			(), ['old-pdb']),
	Options.Boolean('old-dlp', 0, _("use old DLP access code"), None,
			(), ['old-dlp']),
	Options.Boolean('debug', 0, _("enable debugging code"), None, (), ['debug']),
	]
    
    def __init__(self):
	Sulfur.Application.Application.__init__(self)

	self.port = None
	self.default_user = None
	self.default_uid = None
	self.user = None
	self.uid = None
	self.sync_id = None
	self.remote = None
	
	self.state = {}

	self.plugin_module_path.insert(0, 'Pyrite')
	
    def prerun(self):
	r = self.registry
#	r = Registry.Registry()
#	self.registry = r
#	r.load('/etc/palm.conf', 'SYSTEM')
#	r.load(os.path.expanduser('~/.palm.conf'), 'USER')

	# Pyrite default plugin path
#	pp = r.get('Pyrite::plugin-packages',[])
#	if type(pp) != type([]): pp = [ pp ]
#	for p in pp: self.plugin_module_path.append(p)
	
	## FIXME do something intelligent with ports

	# first, we try environment variables.
	if os.environ.has_key('PYRITEPORT'):
	    self.port = os.environ['PYRITEPORT']
	elif os.environ.has_key('PILOTPORT'):
	    self.port = os.environ['PILOTPORT']
	else:
	    # select default port
	    if r.has_key('defaults::default-port'):
		self.port = r.get('defaults::default-port')
		if type(self.port) == type([]):
		    if self.port:
			self.error(_("defaults::default-port option should not be a list."),'warning')
			self.error(_("using %s as the default port.") % self.port[0], 'warning')
			self.port = self.port[0]
		    else:
			self.error(_("defaults::default-port is an empty list."),'warning')
			self.port = None
	    else:
		p = r.get('defaults::port','')
		if type(p) == type([]):
		    if p:
			self.port = p[0]
		    else:
			self.error(_("defaults::port is an empty list."),'warning')
			self.port = None
		else:
		    # backward compatibility
		    if ',' in p: self.port = string.strip(string.split(p, ',')[0])
		    else: self.port = p

	if not self.port:
	    self.error(_("no port specified in config file, using /dev/pilot"),'warning')
	    self.port = '/dev/pilot'

	if os.environ.has_key('PYRITEPATH'):
	    self.data_directory = os.environ['PYRITEPATH']
	else:
	    self.data_directory = os.path.expanduser(r.get('defaults::data-directory',''))
	if not self.data_directory:
	    self.error(_("no data directory specified, using ~/Palm"),'warning')
	    self.data_directory = os.path.expanduser('~/Palm')
	_mkdir(self.data_directory)
	pydir = os.path.join(self.data_directory, 'Pyrite')
	_mkdir(pydir)
	# get saved state
	try:
	    self.state = pickle.load(open(os.path.join(pydir,'state'),'r'))
	except:
	    self.state = {}
	# if the user and uid are specified in the conf file,
	# we use them.  otherwise, use the ones in the state.
	if os.environ.has_key('PYRITEUSER'):
	    self.default_user = os.environ['PYRITEUSER']
	else:
	    self.default_user = r.get('defaults::user',self.state.get('user',None))
	if os.environ.has_key('PYRITEUID'):
	    self.default_uid = os.environ['PYRITEUID']
	else:
	    self.default_uid = r.get('defaults::uid',self.state.get('uid',None))

	# some defaults
	if not self.default_uid:
	    self.error(_("no default user specified"),'warning')

	if self.default_uid and self.default_user and not self.user_exists(self.default_uid):
	    self.user_add(self.default_uid, self.default_user)
	    
	# make a new PC ID if there isn't one already, or if the state file was
	# written with a different version of Pyrite.  (This makes sure to do
	# a slow sync in case there have been any changes to Pyrite which might
	# affect the fast sync logic or database contents etc.)
	if not self.state.has_key('syncid') or \
	   not self.state.has_key('pyrite_version') or \
	   (self.state['pyrite_version'] != Pyrite.version):
	    from whrandom import randint
	    self.state['syncid'] = (randint(0, 65535) << 16 | randint(0, 65535))

	self.sync_id = self.state.get('syncid',0)

	# add products
	if self.state.has_key('products'):
	    prd = {}
	    for pkg in self.state['products'].values():
		# in the future, we will need to import all packages here,
		# to check for callbacks.
		if pkg and pkg not in self.plugin_module_path:
		    self.plugin_module_path.append(pkg)
		    
	self.change_user(self.default_uid)

    def postrun(self):
	self.state['user'] = self.user
	self.state['uid'] = self.uid
	self.state['syncid'] = self.sync_id
	self.state['pyrite_version'] = Pyrite.version
	if self.data_directory:
	    _mkdir(self.data_directory)
	    _mkdir(os.path.join(self.data_directory, 'Pyrite'))
	    try:
		pickle.dump(self.state, open(os.path.join(self.data_directory,'Pyrite',
							  'state'),'w'))
	    except:
		pass

	if self.connected(): self.disconnect()
	
#    def configure_user(self):
#	if not self.user: return
#	if self.registry.label() == 'PALMUSER':
#	    self.registry.pop()
#
#	if not self.user_exists(self.user, self.uid):
#	    self.error(_("palmtop user '%s' does not have a directory; creating one"))
#	    self.user_add(self.user)
#	    
#	try:
#	    d = find_user_directory(self.data_directory, self.user, self.uid)
#	except:
#	    self.error(_("user '%s' might not exist") % self.user, 'error')
#	    return
#
#	if d is None:
#	    self.error(_("user directory for '%s' not found") % self.user, 'error')
#	    return
#	
#	self.registry.load(os.path.join(d, 'palm.conf'), 'PALMUSER')
#	self.configure(self.registry)
#
#	for p in self.plugins.values():
#	    p.configure(self.registry)
	    
    # ----------------------------------------------------------------
    # Connection Stuff
    #
    # Instantiating a DLP Store does not actually connect to the device;
    # connection is deferred until the application actually does something
    # with the Store, at which point the preconnect and postconnect
    # functions are called at the appropriate time.
    # ----------------------------------------------------------------
    def preconnect(self, *a, **kw):
	print _("Waiting for connection on %s (start the HotSync(R) application now)...") % self.port

    def postconnect(self, store, *a, **kw):
	self.log(_("Identifying user..."))
	
	uinfo = store.user_info
	self.log(_("User Name: %s") % uinfo['name'])
	self.log(_("Last Sync: %s") % time.ctime(uinfo['lastSyncDate']))
	self.log(_("Last Successful Sync: %s") % time.ctime(uinfo['successfulSyncDate']))
	self.log(_("UID: %s  VID: %s  LastSyncPC: 0x%08x") % (uinfo['userID'],
							   uinfo['viewerID'],
							   uinfo['lastSyncPC']))

	self.connect_user()

    def connect(self, immediate=0):
	"""Instantiate a remote store."""
	if self.get_option('old-dlp'):
	    p = self.get_plugin('Store','OldDLP')
	else:
	    p = self.get_plugin('Store','DLP')
	self.remote = p(self.port, 0, self.preconnect, self.postconnect)
	if immediate: self.remote.connect()
	return self.remote

    def disconnect(self, successful=1, log=_("Sync completed.")):
	self.remote.disconnect(successful, log)

    def connected(self):
	return self.remote is not None and self.remote.connected()
	
    # get something from the registry
    # get an appmodule
    # spool something for later install

    def user_path(self, name=None, uid=None):
	if uid is None: uid = self.uid
	if not self.uid:
	    raise RuntimeError, _("uid is zero")
	if name:
	    return os.path.join(self.data_directory, str(uid), name)
	else:
	    return os.path.join(self.data_directory, str(uid))
	
    
    def user_directory(self, dir='backup', make=1, uid=None):
	"""Access a specific user data directory.

	Returns an appropriate Directory Store object.
	If the 'make' parameter is true (the default), and the
	directory doesn't exist, it will be created.
	"""
	if uid is None: uid = self.uid
	if not uid:
	    raise RuntimeError, _("uid is zero")
	path = os.path.join(self.data_directory, str(uid), dir)
	if make: _mkdir(path)
	if self.get_option('old-pdb'):
	    p = self.get_plugin('Store','OldDirectory')
	else:
	    p = self.get_plugin('Store','Directory')
	s = p(path)
	return s

    # issue: expand to handle deeper levels?
    # do we even need this function?
    def user_directories(self):
	"""List all available top-level user directories.
	"""
	p = os.path.join(self.data_directory, str(self.uid))
	return filter(lambda x, path=p: os.path.isdir(os.path.join(path, x)),
		      os.listdir(p))

    def open(self, name, mode='rs', dbclass=Database, **kw):
	"""Open an arbitrary database.
	This function can take either a filename or a URL as its argument.
	The following URL types are acceptable:
	    http -- database is fetched and opened read-only
	    ftp  -- database is fetched and opened read-only
	    file -- equivalent to filename if on 'localhost', otherwise
	            tries ftp
	    user -- open a database in a user directory:
	      user://username/directory/databasename

	If attempting to open by filename fails, this function then tries
	to open by *database name* in the current directory.
	"""
	scheme, loc, path, param, query, frag = urlparse.urlparse(name)
	if scheme == 'user':
	    user = urllib.unquote(loc)
	    path, n = os.path.split(path)
	    if path and path[0] == '/': path = path[1:]
	    if not user: user = self.user
	    if not path: path = 'backup'
	    # avoid unnecessary making of directories
	    if 'w' in mode: make = 1
	    else: make = 0
	    try:
		u = int(user)
	    except:
		u = self.user_lookup(user)
	    if not u:
		raise RuntimeError, _("user '%s' not found") % user
	    s = self.user_directory(path, make, u)
	    return apply(s.open, (n,mode,dbclass), kw)
	elif scheme in ['http','ftp'] or \
	     (scheme == 'file' and loc and loc != 'localhost'):
	    p = self.get_plugin('Store','URL')
	    s = p(name)
	    l = s.list()  # this actually fetches the file, it is now cached
	    return apply(s.open, (name,mode,dbclass), kw)
	else:
	    if scheme == 'file': name = path
	    
	    if self.get_option('old-pdb'):
		p = self.get_plugin('Store','OldFile')
	    else:
		p = self.get_plugin('Store','File')
	    s = p(name)
	    l = s.list()
	    # if this isn't a valid filename, try opening it as a
	    # database name instead.
	    if not l:
		path, n = os.path.split(name)
		if self.get_option('old-pdb'): p = self.get_plugin('Store','OldDirectory')
		else: p = self.get_plugin('Store','Directory')
		s = p(path)
		name = n
	    return apply(s.open, (name,mode,dbclass), kw)

    # --------------------------------------
    # User Management
    # --------------------------------------

#    def user_exists(self, user, uid=None):
#	return find_user_directory(self.data_directory, user, uid) is not None
#
#    def user_add(self, user, uid=None):
#	d = user_directory_name(self.data_directory, user, uid)
#	_mkdir(d)
#	_mkdir(os.path.join(d, 'backup'))
#	_mkdir(os.path.join(d, 'install'))
#
#    def user_delete(self, user, uid=None):
#	import shutil
#	d = find_user_directory(self.data_directory, user, uid)
#	if d:
#	    shutil.rmtree(d, 1)
#
#    def user_rename(self, user, newuser, uid=None, newuid=None):
#	d = find_user_directory(self.data_directory, user, uid)
#	n = user_directory_name(self.data_directory, newuser, newuid)
#	os.rename(d, n)
#
#    def user_list(self):
#	l = []
#	d = os.getcwd()
#	os.chdir(self.data_directory)
#	for dir in filter(os.path.isdir, os.listdir('.')):
#	    os.chdir(os.path.join(self.data_directory, dir))
#	    # simple rule to determine if this is probably a known user
#	    if os.path.isdir('backup') and os.path.isdir('install'):
#		l.append(unprotect_name(dir))
#	os.chdir(d)
#	l.sort()
#	return l

    # user management, take two

    # note: assumes self.remote is connected already
    def connect_user(self):
	user = self.remote.user_info['name']
	uid = self.remote.user_info['userID']
	rewrite = 0
	
	if not user and not uid:
	    self.error(_("Pyrite does not support unidentified palmtops (yet)"))
	    return

	if not uid:
	    uid = (randint(0, 65535) << 16 | randint(0, 65535))
	    self.error(_("Palm user ID is zero.  Assigning a new one (%d).") % uid, 'warning')
	    rewrite = 1
	    
	if not self.user_exists(uid):
	    self.user_add(uid, user)
	    un = user
	else:
	    un = self.user_name(uid)

	    if user != un:
		self.error(_("Palm user name does not match.  Restoring."), 'warning')
		self.error(_("'%s' / '%s'") % (user, un))
		user = un
		self.remote.user_info['name'] = un

	self.change_user(uid)
	
    # change users.  note that the user has to exist!
    def change_user(self, uid):
	if self.registry.label() == 'PALMUSER': self.registry.pop()
	if not uid:
	    return
	if not self.user_exists(uid):
	    raise RuntimeError, _("user #%d is unknown") % uid
	self.uid = uid
	self.user = self.user_name(uid)

	self.registry.load(os.path.join(self.data_directory, str(uid), 'Pyrite', 'palm.conf'),
			   'PALMUSER')

	for p in self.plugins.values():
	    p.configure(self.registry)

    def user_add(self, uid, user):
	ud = os.path.join(self.data_directory, str(uid))
	# set up pyrite for a new user
	_mkdir(ud)
	_mkdir(os.path.join(ud, 'backup'))
	_mkdir(os.path.join(ud, 'install'))
	_mkdir(os.path.join(ud, 'Pyrite'))

	if not user:
	    self.error(_("This palmtop has an empty user name."), 'warning')
	    user = ''  # just in case it's None
	open(os.path.join(ud, 'NAME'), 'w').write(user)

    def user_name(self, uid):
	try:
	    s = open(os.path.join(self.data_directory, str(uid), 'NAME')).readline()
	    if s[-1] == '\n': return s[:-1]
	    else: return s
	except:
	    return ''

    def user_exists(self, uid):
	return os.path.isdir(os.path.join(self.data_directory, str(uid)))
    
    def user_list(self):
	l = []
	_d = os.getcwd()
	os.chdir(self.data_directory)
	for dir in filter(os.path.isdir, os.listdir('.')):
	    try:
		id = int(dir)   # will throw exception if not a numeric dir name
		l.append(id)
	    except:
		continue
	os.chdir(_d)
	l.sort()
	return l

    def user_lookup(self, name):
	for i in self.user_list():
	    if self.user_name(i) == name: return i
	return 0
    
    # ---------------------------
    # Application Data Management
    # ---------------------------
    def app_path(self, path=None):
	p = os.path.join(self.data_directory, self.app_prefix)
	_mkdir(p)
	if path: p = os.path.join(p, path)
	return p

    def app_user_path(self, path=None, uid=None):
	if uid is None: uid = self.uid
	if not uid:
	    raise RuntimeError, _("uid is zero")
	p = os.path.join(self.data_directory, str(uid), self.app_prefix)
	_mkdir(p)
	if path: p = os.path.join(p, path)
	return p

    def user_open(self, name, mode='r', uid=None):
	p = self.user_path(name, uid)
	return open(p, mode)
    
    def app_open(self, name, mode='r'):
	p = self.app_path(name)
	return open(p, mode)

    def app_user_open(self, name, mode='r', uid=None):
	p = self.app_user_path(name, uid)
	return open(p, mode)

#      # products: a product is a Pyrite add-on which provides plug-ins.
#      # it is assumed to already be locatable on the Python path, and
#      # these functions merely allow Pyrite to be aware that it exists
#      # so that it can add all products to its search path
#      # automatically.

#      def product_install(self, package):
#  	if not self.state.has_key('products'):
#  	    self.state['products'] = {}

#  	try:
#  	    m = misc.import_module(package)
#  	except:
#  	    m = None

#  	if not m:
#  	    raise ImportError, _("Could not import package '%s'") % package

#  	if not hasattr(m, 'PYRITE_PRODUCT'):
#  	    raise RuntimeError, _("Package '%s' does not appear to contain a Pyrite product.") % package

#  	name = m.PYRITE_PRODUCT['name']
	
#  	if package not in self.plugin_module_path:
#  	    self.plugin_module_path.append(package)

#  	self.state['products'][name] = package

#  	return name

#      def product_list(self):
#  	if not self.state.has_key('products'):
#  	    self.state['products'] = {}

#  	l = []
#  	for name, pkg in self.state['products'].items():
#  	    try:
#  		m = misc.import_module(pkg)
#  	    except:
#  		continue
#  	    if not hasattr(m, 'PYRITE_PRODUCT'):
#  		continue
#  	    q = {'package': pkg,
#  		 'name': m.PYRITE_PRODUCT.get('name'),
#  		 'author': m.PYRITE_PRODUCT.get('author'),
#  		 'version': m.PYRITE_PRODUCT.get('version'),
#  		 'description': m.PYRITE_PRODUCT.get('description')
#  		 }
#  	    l.append(q)
#  	l.sort(lambda x,y: cmp(x.get('name'),y.get('name')))
#  	return l

#      def product_remove(self, name):
#  	if not self.state.has_key('products'):
#  	    self.state['products'] = {}

#  	if self.state['products'].has_key(name):
#  	    p = self.state['products'][name]
#  	    if p and p in self.plugin_module_path:
#  		self.plugin_module_path.remove(p)
#  	    del self.state['products'][name]

#      def product_installed(self, name):
#  	return self.state['products'].has_key(name)

#      def product_info(self, name):
#  	for p in self.product_list():
#  	    if p['name'] == name: return p
#  	return {}
    

    # Backward compatibility (temporary overrides)
    def get_plugin(self, collection, name, *a, **kw):
	if collection == 'App':
	    self.error(_("using deprecated name for application modules; should be 'Connector', not 'App'"), 'warning')
	    collection = 'Connector'
	return apply(Sulfur.Application.Application.get_plugin, (self, collection, name)+a, kw)

    def __call__(self, *a, **kw):
	ctx = PyriteCLIAppContext(self)
	apply(ctx, a, kw)

class PyriteState(AppContext.PickleState):
    def start(self, context):
	AppContext.PickleState.start(self, context)
	context.registry.load('/etc/palm.conf', 'SYSTEM')
	context.registry.load(os.path.expanduser('~/.palm.conf'), 'USER')


class PyriteCLIAppContext(AppContext.CLIAppContext):
    app_type = 'Pyrite'
    def __init__(self, *a, **kw):
	apply(AppContext.CLIAppContext.__init__, (self,)+a, kw)
	self.state_manager = PyriteState()
	
