#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#Purpose:
#Used in conjunction with a Konqueror service menu to allow multiple url selection
#when attaching to email.
#
#Author:
#Dylan Schrader <dschrader@conception.edu>
import sys
import os
import dircache
import commands
from string import *

#Default values
emailclient="$(kde-config --prefix)/bin/kmail -s %s --body %B --attach %A"
language="en"
kdeprefix=commands.getoutput("kde-config --prefix")
kdelocalprefix=commands.getoutput("kde-config --localprefix")
#Path to kde email configs.
emailconfigfile="%s/share/config/emaildefaults" % kdelocalprefix
#Path to kde language configs.
langconfigfile="%s/share/config/kdeglobals" % kdelocalprefix
#Various language options.
languages={
"en":{"subject":"Attached files","body":"Attached should be:"},
"cs":{"subject":u"Přiložené soubory","body":u"V příloze je/jsou:"},
"sk":{"subject":u"Priložené súbory","body":u"V prílohe je/sú:"},
"la":{"subject":"Scapis iniunctis","body":"Quae erant iniungenda:"},
"de":{"subject":"Angeh\344ngte Dateien","body":"Angeh\344ngt werden:"},
"pt_BR":{"subject":"Arquivos anexos","body":u"Os anexos são:"},
"nl":{"subject":"Bijgesloten bestanden","body":"De volgende bestanden zijn bijgesloten:"},
"pl":{"subject":u"Pliki w załączniku","body":u"Załączone pliki:"},
"es":{"subject":"Incluye archivos","body":"Este correo debe incluir los archivos:"},
"da":{"subject":u"Vedhæftede filer","body":u"Vedhæftede filer er:"},
"nb":{"subject":" Vedlagde filer","body":" Vedlagde filer er:"},
"nn":{"subject":" Vedlagde filer","body":" Vedlagde filer er:"}
}
#Attachments.
attachments=""
#The arguments.
attachmentlist=sys.argv[1:]

def urlsafe(x):
	"""Make string x safe for urls."""
	y=""
	for char in x:
		if not char in ascii_letters+digits+os.sep:
			char="%"+str(hex(ord(char)))[2:]
		y+=char
	return y

def parseconfig(option,configs):
	"""Parse configs(list of lines) for option."""
	value=""
	for line in configs:
		line=line.strip()
		if find(line,option)==-1:
			continue
		value=line[len(option):].lstrip().lstrip("=").lstrip()
	return value

def openconfig(file):
	"""Open a config file and return a list of lines in it."""
	try:
		o=open(file,"r")
		configlines=o.readlines()
		o.close()
		print "Config file found in %s" % (file)
	except:
		configlines=[]
		print "No config file found in %s" % (file)
	return configlines

configlines=openconfig(emailconfigfile)
value=parseconfig("EmailClient",configlines)
if value!="" and os.path.basename(value)!="kmail":
	emailclient=value

configlines=openconfig(langconfigfile)
value=parseconfig("Language",configlines)
if languages.has_key(value):
	language=value
elif languages.has_key(value[:2]):
	#Suppose that you use en_US, but languages only has_key("en").
	language=value[:2]

subject=languages[language]["subject"]
body=languages[language]["body"]

for path in attachmentlist:
	if os.path.isdir(path):
		#If it's a directory, we want to include all subpaths recursively.
		#Change this if you want it to do something else (e.g. tar the directory, then attach it.)
		files=dircache.listdir(path)
		for file in files:
			attachmentlist.append(os.path.join(path,file))
	else:
		body+="\n\t%s" % (path)
		if os.path.isabs(path):
			#if it's a local file (and not http,ftp,etc)
			if os.path.split(split(emailclient)[0])[1]=="kmail":
				#kmail will interpret http char codes even for local files;
				#this compensates for that.
				path=urlsafe(path)
		attachments+=" \'%s\'" % (path)

executable=emailclient
executable=replace(executable,"%s","\'"+subject+"\'")
executable=replace(executable,"%B","\'"+body+"\'")
executable=replace(executable,"%A",attachments)
executable=replace(executable,"%t","")
executable=replace(executable,"%c","")
executable=replace(executable,"%b","")

try:
	print "Executing: %s" % (executable)
	os.system(executable)
except UnicodeEncodeError:
	executable=executable.encode("ascii","replace")
	print "Environment does not support utf-8 encoding."
	print "Converted to ASCII encoding."
	print "Executing: %s" % (executable)
	os.system(executable)