import getopt
import os
import re
import shutil
from subprocess import Popen,PIPE
import sys

# If you are adding prefs that require string values (rather than true/false),
# be sure to wrap the string value in quotes, e.g.:
# 'browser.active_color': '"#EE0000"',
userPrefs = {
    'browser.chrome.favicons': 'false',
    'browser.chrome.site_icons': 'false',
    'browser.dom.window.dump.enabled': 'true',
    'browser.sessionstore.resume_from_crash': 'false',
    'browser.shell.checkDefaultBrowser': 'false',
    'browser.tabs.warnOnClose': 'false',
    'browser.warnOnQuit': 'false',
    'dom.allow_scripts_to_close_windows': 'true',
    'dom.disable_open_during_load': 'false',
    'dom.disable_window_flip': 'false',
    'dom.disable_window_move_resize': 'false',
    'layout.fire_onload_after_image_background_loads': 'true',
    'javascript.options.showInConsole': 'true',
    'layout.debug.enable_data_xbl': 'true',
    'shell.checkDefaultClient': 'false',
    'browser.EULA.override': 'true'
}

def usage():
    print "python " + sys.argv[0] + " --binary=binary_location [--profileName=default] [--clobber] [--help]" 

def runCreateProfile(binary,profileName):
    cmd = binary + " -CreateProfile " + profileName
    p = Popen(cmd, 
              shell=True, 
              stdin=PIPE, 
              stdout=PIPE, 
              stderr=PIPE)
    for line in p.stderr:
        m = re.search('Success: created profile .* at \'([^\']+)\'',
                      line)
        if m:
            return m.group(1)
    return ""

def populatePrefs(profileLocation):
    try:
        f = open(profileLocation, 'w')
    except IOError:
        print "Couldn't write to " + profileLocation
        sys.exit(2)
    f.write("/* Generated by buildbot */\n\n")
    for key in userPrefs.keys():
        f.write('user_pref("' + key + '", ' + userPrefs[key] + ");\n")
    f.close()
    print "Wrote testing preferences to %s" % profileLocation

def main(argv):
    try:
        opts, args = getopt.getopt(argv, 
                                   "hb:p:cd", 
                                   ["help", 
                                    "binary=", 
                                    "profileName=",
                                    "clobber"])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    binary = ""
    profileName = "default"
    clobber=0
    for o,a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        if o in ("-b","--binary"):
            binary=a
        if o in ("-p","--profileName"):
            profileName=a
        if o in ("-c","--clobber"):
            clobber=1
    if binary=="" or not os.path.exists(binary):
        usage()
        sys.exit(2)

    profileLocation = runCreateProfile(binary,profileName)
    if not profileLocation or not os.path.exists(profileLocation):
        print "Couldn't find profile location"
        sys.exit(2)
    # Delete the existing profile directory if clobber is requested.
    # -CreateProfile will re-create it in the right place.
    if clobber:
        dirname = os.path.dirname(profileLocation)
        shutil.rmtree(dirname)
        profileLocation = runCreateProfile(binary,profileName)
        if not profileLocation or not os.path.exists(profileLocation):
            print "Couldn't find profile location on second pass"
            sys.exit(2)

    populatePrefs(profileLocation)

if __name__ == "__main__":
    main(sys.argv[1:])
