# Flash Plugin Switcher 1.1.3
# http://mattshaw.org/projects/flash-plugin-switcher
# GPL License http://www.gnu.org/licenses/gpl.html

import os, sys, platform, shutil, dircache, urllib2, datetime, time

WIN = 'windows'
LINUX = 'linux'
MAC = 'mac'

ACTIVE_PLUGIN_FOLDER = {
 	WIN: 	'C:/Windows/System32/Macromed/Flash/',
	MAC:	r'/Library/Internet Plug-Ins/',
	LINUX:	 '~/.mozilla/plugins/'
}

FILES_TO_COPY = {
	WIN: 	( 'flashplayer.xpt', 'NPSWF32.dll' ),
	MAC:	( 'flashplayer.xpt', 'Flash Player.plugin/'), # '._Flash Player.plugin',
	LINUX:	( 'libflashplayer.so', )
}

THIS_FOLDER = sys.path[0].replace('\\','/')

PLUGINS_ARCHIVE = THIS_FOLDER + '/plugins/'

VERSION = 6

PROJECT_URL = 'http://mattshaw.org/projects/flash-plugin-switcher/'
UPDATE_URL = 'http://mattshaw.org/projects/flash-plugin-switcher/version.php'

LOG = 'update.log'

###

def initPlatform():
	global MAC, ACTIVE_PLUGIN_FOLDER, ACTIVE_PLUGIN_FOLDER, PLUGINS_ARCHIVE, FILES_TO_COPY
	p = platform.system().lower()
	if p=='darwin': p=MAC
	FILES_TO_COPY = FILES_TO_COPY[p]
	ACTIVE_PLUGIN_FOLDER = ACTIVE_PLUGIN_FOLDER[p]
	PLUGINS_ARCHIVE += p + '/'

def checkPluginsFolder():
	global UPDATE_URL, VERSION
	if not os.path.exists(PLUGINS_ARCHIVE):
		print ""
		print "Couldn't find plugins folder. There should be a 'plugins' folder with this script. Did you download any plugins?"
		print PROJECT_URL
		print ""
		enterToContinue()

def firstRun():
	global LOG
	return not os.path.exists(LOG)

def checkUpdate():
	global UPDATE_URL, PROJECT_URL, LOG
	
	last_check = 0
	if os.path.exists(LOG):
		f = open(LOG,'r')
		last_check = int(f.read())
		f.close()
	
	week_seconds = 604800

	now = int(time.time())
	if not last_check or last_check+week_seconds < now:
		f = open(LOG,'w')
		f.write(str(now))
		f.close()
		try:
			f = urllib2.urlopen(UPDATE_URL)
			latest =  int(f.read())
			f.close()
			if latest > VERSION:
				print "There's a newer version of this script available at %s" % PROJECT_URL
				print "I'll remind you again in a week."
				enterToContinue(False)
				clearScreen()
		except:
			pass

def delFile(file_name):
	if os.path.exists(file_name): 
		print "Deleting %s" % file_name
		try:
			os.remove(file_name)
		except:	
			#print sys.exc_info()[1]
			try:
				shutil.rmtree(file_name)
			except:
				print "\nError deleteing %s\nIs your browser still open?" % file_name
				enterToContinue()

def backup(file_name):
	# This is confusing Firefox. I think the backups have to go in a different folder.
	#backup_file = "%s.bak" % file_name
	#delFile(backup_file
	delFile(file_name)
	return 0
	#if os.path.exists(file_name): 
	#	print "Backing up %s" % file_name
	#	shutil.move(file_name,backup_file)
	#	delFile(file_name)

def copyPlugin(src_folder,dest_folder):	
	print "Copying to %s" % dest_folder
	global PLUGINS_ARCHIVE, FILES_TO_COPY
	for file_name in FILES_TO_COPY:
		src_path = src_folder+file_name
		dest_path = dest_folder+file_name
		# pre 9.0 don't have flashplayer.xpt
		if file_name=='flashplayer.xpt' and not os.path.exists(src_path): continue
		try:
			# backup plugin we are overwriting
			backup(dest_path)
			if file_name.endswith('/'):		
				fileFunc = shutil.copytree
			else:							
				fileFunc = shutil.copyfile

			# copy file(s)
			#print "Copying %s" % file_name
			print "%s -> %s" % (src_path,dest_path)
			fileFunc(src_path,dest_path)

		except IOError, e:
			print "Error copying! ", e
			print ""
			return 1
	
	return 0

def promptForSelection(msg,options):
	clearScreen()
	while 1:
		print "%s\n" % msg
		for i in range(len(options)): print "%s) %s" % (i+1,options[i])
		raw = raw_input("\n>").strip()
		if raw=='exit': sys.exit()
		i = int( raw )
		i -= 1
		if i>=0 and i<len(options):
			break
		print "\nInvalid selection\n"
	return i

def checkFirstRun():
	if firstRun():
		i = promptForSelection("Looks like this is your first time running this script. Do you want to backup your current Flash plugin?",
			("Yes","No")
		)
		if i==0:
			askBackup()
			enterToContinue(False)

def askSwitch():
	global FILES_TO_COPY, ACTIVE_PLUGIN_FOLDER, PLUGINS_ARCHIVE
	raw_input("\nHit enter to confirm your browsers are closed. (Firefox, Safari, Chrome, Opera)\n")

	# get plugins available, filter bullshit
	files = [f for f in dircache.listdir(PLUGINS_ARCHIVE) if not f.startswith('.')]

	# prompt user
	i = promptForSelection("Choose a plugin to restore: ",files)
	subfolder = PLUGINS_ARCHIVE + files[i] + '/'

	print ''
	print 'Attempting to copy %s' % subfolder
	print '...'

	# try to copy plugin
	err = copyPlugin( subfolder, ACTIVE_PLUGIN_FOLDER )
	if err:	print "There was an error. Is your browser still open?"
	else:	print "\nDone"

def askBackup():
	global ACIVE_PLUGIN_FOLDER,PLUGINS_ARCHIVE
	import re
	while 1:
		plug_name = raw_input("\nEnter a name for your current plugin (e.g. 10.2 Debug). \nYou can find out your Flash version at http://www.adobe.com/software/flash/about/\n>").strip()
		plug_name = re.sub(r'[^a-zA-Z0-9\. ]+','',plug_name)
		if len(plug_name)>0: break
	dest_path = PLUGINS_ARCHIVE + plug_name + "/"
	os.makedirs(dest_path)
	copyPlugin( ACTIVE_PLUGIN_FOLDER, dest_path )
	print "\nDone"

def showHelp():
	clearScreen()
	print """
This script will switch your current Flash plugin with a backed up version.
Where do you get the backed up version? The backed up version comes from you!
For example, you install Flash 10.2. Then you run this script, select option (2) 
to backup the 10.2 plugin. Then later you can restore the 10.2 plugin using this script.

"""
	enterToContinue(False)
	showMenu()

def showMenu():
	MENU = (
		('Switch my current plugin.',askSwitch),
		('Backup my current plugin for later use.',askBackup),
		('Help',showHelp)
	)

	options, funcs = zip(*MENU)

	i = promptForSelection("Select an option above: ",options)

	funcs[i]()

def enterToContinue(exit=True):
	if exit: msg = 'Press enter to exit...'
	else:	 msg = 'Hit enter to continue...'
	raw_input('\n%s'%msg)
	if exit: sys.exit()

def clearScreen():
	print "\n" * 100

###

clearScreen()
initPlatform()
checkFirstRun()
checkUpdate()
checkPluginsFolder()
showMenu()
enterToContinue()