# Gdsk! Patcher for gOS
# 1.0

import os
import sys
import shutil
import urllib

# first string contains file, second contains URL to patch, third is new URL
# todo: figure out how to patch weather globe
files = [
	["/usr/lib/google-gadgets/modules/google-gadget-manager.so", "https://clients2.google.com/desktop/plugins.xml?platform=linux&cv=5.7.0.0", "http://gdsk2.retrosite.org/desktop/plugins.xml?platform=linux&cv=5.7.0.01"],
	["/usr/lib/google-gadgets/modules/google-gadget-manager.a", "https://clients2.google.com/desktop/plugins.xml?platform=linux&cv=5.7.0.0", "http://gdsk2.retrosite.org/desktop/plugins.xml?platform=linux&cv=5.7.0.01"],
	["/usr/share/google-gadgets/google-gadget-browser/plugins.js", "desktop.google.com", "gdsk.retrosite.org"],
	["/usr/share/google-gadgets/google-gadget-browser/thumbnail.js", "desktop.google.com", "gdsk.retrosite.org"],
	["/usr/share/google-gadgets/digital_alarm_clock/main.js", "maps.google.com", "gdsk.retrosite.org"],
];

aptStrings = [
    ["/etc/apt/sources.list" "us.archive.ubuntu.com", "old-releases.ubuntu.com"],
    ["/etc/apt/sources.list" "security.ubuntu.com", "old-releases.ubuntu.com"]
];

# the function that actually does the patching
def patch(index):
	path = index[0]
	url = index[1]
	newurl = index[2]
    
	# check if file has already been patched
	if os.path.exists(path + ".origgdsk"):
		# not doin that
		print(" * " + path + " has already been patched. Skipping...")
		return

	print(" * Patching " + path)
    
	# make a copy of the file that we'll work with, for safety's sake
	shutil.copy(path, path + ".tmpgdsk")

	file = open(path + ".tmpgdsk", "r+")

	content = file.read()

	# no way i'd be able to get away with this in any other language on any other OS, but it seems to work here
	# i'll just take the win and not overcomplicate things
	content = content.replace(url, newurl)
    
	# PLEASE GOD MAKE SURE YOU SEEK TO THE BEGINNING OF THE FILE
	# todo: maybe we want to seek to each position in the file and write the string there, but i am lazy
	file.seek(0)
	file.write(content)
	file.close();
    
	# shuffle some files around
	# first off, rename the original (unmodified) file
	os.rename(path, path + ".origgdsk")

	# now, rename our patched file to replace the original
	os.rename(path + ".tmpgdsk", path)

	#print(path + " patched!")

# loop through the list of files and do em all
def patchAll():
	for i in files:
		patch(i)
        
def patchApt():
	path = "/etc/apt/sources.list";
	patches = ["us.archive.ubuntu.com", "security.ubuntu.com"]
    
	# check if file has already been patched
	if os.path.exists(path + ".origgdsk"):
		# not doin that
		print(" * " + path + " has already been patched. Skipping...")
		return
        
	print(" * Patching " + path)

	# make a copy of the file that we'll work with, for safety's sake
	shutil.copy(path, path + ".tmpgdsk")

	file = open(path + ".tmpgdsk", "r+")

	content = file.read()

	for i in patches:
		content = content.replace(i, "old-releases.ubuntu.com")

	# PLEASE GOD MAKE SURE YOU SEEK TO THE BEGINNING OF THE FILE
	# todo: maybe we want to seek to each position in the file and write the string there, but i am lazy
	file.seek(0)
	file.write(content)
	file.close();
    
	# shuffle some files around
	# first off, rename the original (unmodified) file
	os.rename(path, path + ".origgdsk")

	# now, rename our patched file to replace the original
	os.rename(path + ".tmpgdsk", path)
    

def main():
	# check for linux
	if sys.platform != "linux2":
		print(" * This tool is designed for gOS 3.1 only.")
		raw_input(" * Press Enter to quit.");
		exit()

	# check for sudo
	if os.geteuid() != 0:
		print(" * This tool must be run as sudo. Append sudo to the beginning of the launch command and try again.")
		raw_input(" * Press Enter to quit.");
		exit()
		
	print(" * Welcome to the Gdsk! Patcher for gOS!\n\n * Before continuing, please ensure that Google Gadgets is not running.\n * You can do this by looking for the gadgets icon in the tray on the top right of the screen.\n\n * WARNING: This patcher is designed for gOS 3.1 only. It may work on other systems running Google Gadgets, however it has not been tested. If you are not running gOS 3.1, continue at your own risk.\n")
	
	raw_input(" * Press Enter to continue...")

	patchAll()
	
	# clear out the old default plugins.xml
	xmlpath = os.path.expanduser("~/.google/gadgets/plugins.xml")
    
	if os.path.exists(xmlpath):
		# bug: right now, we're relying on the original plugins.xml to maintain correct file permissions.
		# if for some reason the XML weren't there, then it would be created with the owner as root, preventing google gadgets from updating it
		# there should be no reason that the XML doesn't exist, but just in case only offer to download if it does
		downloadPlugins = raw_input(" * Do you want me to download the latest list of gadgets?\n * Eventually Google Gadgets will do this on its own, but it may take a while.\n * (Y for yes, other for no)\n")

		if downloadPlugins.lower() == "y":
			print(" * Downloading the gadget list to " + xmlpath + "\n")
			urllib.urlretrieve("http://gdsk.retrosite.org/desktop/plugins.xml?platform=linux", xmlpath)
		else:
			os.remove(xmlpath)
			print(" * Not downloading the gadget list.\n * In the meantime, you can use the online gadget gallery at:\n * http://gdsk.retrosite.org/plugins\n");
	    
	fixAPT = raw_input(" * Do you want me to fix the gOS package manager as well?\n * (Y for yes, other for no)\n")

	if fixAPT.lower() == "y":
		patchApt();
	else:
		print(" * Not fixing the package manager...");

	print(" * All done! It is now safe to relaunch Google Gadgets.\n\n * Enjoy!\n")

	raw_input(" * Press Enter to quit.");

main()

