#(c) 2004-2008 Thunderstone Media, LLC
#Creative Commons Attribution-Noncommercial 3.0 United States License
#
#Python Developyment By:
#
#Ray Slakinski
#August Trometer

import iPXSettings
import iPXClass
from iPXTools import *

def usage():
	printMSG('\r\n%s' % iPXSettings.USER_AGENT)
	printMSG('-help\r\nPrints this help screen')
	printMSG('\r\n-url=="<feedURL>"\r\nGets just the specified feed URL (must exist in feeds.plist)')
	printMSG('\r\n-id=="<feedID>"\r\nGets just the feed URL associated to the feed ID specified')
	printMSG('\r\n-getEnc=="<feedID>;;<entryGUID>;;<encURL>"\r\nGets just the secified enclosure')
	printMSG('\r\n-updateApps=="<feedID>;;<entryGUID>;;<encGUID>"\r\nAdds the file into the appropriete application')
	printMSG('\r\n-progName=="<programName>"\r\nTells the engine where to find program files')
	printMSG('\r\n-ui\r\nIf the GUI is running the command then it should specifiy this param')
	printMSG('\r\n-initSmartSpace\r\nInitializes cache files for SmartSpace')
	printMSG('\r\n-debug\r\nEnables printing of debug messages to the console')
	printMSG('\r\n-superdebug\r\nEnables printing of debug messages and HTTP traffic information to the console\r\n')

def firstInit():
	import os
	
	iPXSettings.initSettings()
	checkDir(iPXSettings.tmpDownloadDir)
	
	if os.path.isdir(iPXSettings.historyFile):
		logIt('History is a directory? - Resetting history')
		delTree(iPXSettings.historyFile)
		os.removedirs(iPXSettings.historyFile)
		try:
			#Resetting downloadBehavior
			logIt('Resetting downloadBehavior to 3')
			FeedListPrefs	= plistlib.Plist.fromFile(file('%sfeeds.plist' % iPXSettings.rssPath))
			feedDetails = FeedListPrefs['iPodderXFeeds']
			
			for feed in feedDetails:
				feed['downloadBehavior']	= 3
			
			FeedListPrefs.write('%sfeeds.plist' % iPXSettings.rssPath)
		except Exception, msg:
			logIt('ERRMSG: %s' % str(msg))
	
	checkDir(iPXSettings.logPath)
	checkDir(iPXSettings.downloadDirectory)
	checkDir(iPXSettings.rssPath)
	checkDir('%sfeedData/' % iPXSettings.rssPath)
	trimLog()
	iPXSettings.globalProxySetting = setProxy()
	if len(iPXSettings.globalProxySetting) > 0:
		logIt('Proxy Server Detected...')

def main():
	import re, sys
	
	for arg in sys.argv:
		if re.search('-help', arg, re.IGNORECASE):
			gotFeedAlready = True
			usage()
			sys.exit()
	
	iPXSettings.progName = 'iPodderX'
	for arg in sys.argv:
		if re.search('-progName', arg, re.IGNORECASE):
			progNameSplit = arg.split('==')
			iPXSettings.progName = progNameSplit[len(progNameSplit)-1]
	
	firstInit()
	for arg in sys.argv:
		if arg == '-debug':
			printMSG( '--- DEBUG ENABLED ---')
			iPXSettings.DEBUG = 1
		elif arg == '-superdebug':
			printMSG( '--- SUPER DEBUG ENABLED ---')
			import httplib
			httplib.HTTPConnection.debuglevel = 1
			iPXSettings.DEBUG = 1
			iPXSettings.SUPERDEBUG = 1

	try:
		import psyco
		logIt('Enabling Psyco JIT Compiler...')
		psyco.full()
		print passed
	except Exception, msg:
		pass
	
	logIt('\r\n%s Feed Scan Started: %s' % (iPXSettings.USER_AGENT, strftime('%H:%M:%S -- %m/%d/%Y',localtime())))
	logIt('Platform: %s\r\n' % sys.platform)
	if checkReg() == 0:
		logIt('%s is UNREGISTERED' % iPXSettings.USER_AGENT)
		printMSG('APPLICATION_UNREGISTERED\r\n')
		sys.exit(0)
	
	logIt('Params used to launch:')
	for arg in sys.argv:
		if not arg == sys.argv[0]:
			logIt(str(arg))
	
	#Checking to see if the script was run from iPodderX.app or not...
	for arg in sys.argv:
		if re.search('-ui', arg, re.IGNORECASE):
			iPXSettings.ranFromUI = True
			logIt('Feed check being run from UI')
	if iPXSettings.ranFromUI == False:
		if checkForScript() == True:
			sys.exit()
		pass
	
	gotFeedAlready = False
	feedsObj = iPXClass.Feeds()
	if len(feedsObj.feedList) > 0:
		for arg in sys.argv:
			if re.search('-initSmartSpace', arg, re.IGNORECASE):
				from iPXQuotaManager import getAllowedDelList
				printMSG('Generating SmartSpace Data...')
				delTree('%s/iPXCache/' % iPXSettings.tempDir)
				checkDir('%s/iPXCache/' % iPXSettings.tempDir)
				gotFeedAlready = True
				x, y = getAllowedDelList()
				break
			if re.search('-url==', arg, re.IGNORECASE):
				gotFeedAlready = True
				argsSplit = arg.split('==')
				feedsObj.retrFeed(argsSplit[1], 0)
			if re.search('-id==', arg, re.IGNORECASE):
				gotFeedAlready = True
				argsSplit = arg.split('==')
				feedsObj.retrFeed(argsSplit[1], 1)
			if re.search('-getEnc==', arg, re.IGNORECASE):
				gotFeedAlready = True
				iPXSettings.torrentMinDownRate = 0
				argsSplit = arg.split('==')
				temp = argsSplit[1]
				params = temp.split(';;')
				if iPXSettings.ranFromUI:
					#strip quotes off the params...
					param1 = params[0]
					param2 = params[1]
					param3 = params[2]
					param3 = param3.replace('-progName', '')
					param3 = param3.strip()
					feedsObj.retrEnclosure(param1[1:], param2, param3[:len(param3)-1])
				else:
					feedsObj.retrEnclosure(params[0], params[1], params[2])
			if re.search('-updateApps==', arg, re.IGNORECASE):
				gotFeedAlready = True
				argsSplit = arg.split('==')
				temp = argsSplit[1]
				params = temp.split(';;')
				if iPXSettings.ranFromUI:
					#strip quotes off the params...
					param1 = params[0]
					param2 = params[1]
					param3 = params[2]
					feedsObj.retrEnclosure(param1[1:], param2, param3[:len(param3)-1], True)
				else:
					feedsObj.retrEnclosure(params[0], params[1], params[2], True)
		
		if not gotFeedAlready:
			feedsObj.retrFeeds()
	else:
		logIt('feeds.plist in use or empty...')
	
	if not iPXSettings.ranFromUI:
		delTree(iPXSettings.tmpDownloadDir)
	
	printMSG('SUBSCRIPTION_SCAN_COMPLETE')
	logIt('%s Feed Scan Completed: %s' % (iPXSettings.USER_AGENT, strftime('%H:%M:%S -- %m/%d/%Y',localtime())))
	
if __name__ == '__main__':
	main()