#!/usr/bin/python2

import os, sys, commands
import json

priorities = ['yahoo', 'ixquick', 'startpage', 'duckduckgo']

archi = sys.argv[1]
curdir = sys.argv[2]
version = sys.argv[3]
abort = False

release = version
if "+" in version:
    #if "lmde" not in version:
    #    abort = True
    release = version.split("+")[0]

if "~" in version:
    release = version.split("~")[0]

if archi == "amd64":
    archi="linux-x86_64"
else:
    archi="linux-i686"

locales = {}
locales['af'] = 'af'
locales['ar'] = 'ar'
# locales['be'] = 'be'
locales['bg'] = 'bg'
locales['bn-BD'] = 'bn-bd'
locales['ca'] = 'ca'
locales['cs'] = 'cs'
locales['da'] = 'da'
locales['de'] = 'de'
locales['el'] = 'el'
locales['en-GB'] = 'en-gb'
locales['eo'] = 'eo'
locales['es-ES'] = 'es'
locales['et'] = 'et'
locales['eu'] = 'eu'
locales['fa'] = 'fa'
locales['fi'] = 'fi'
locales['fr'] = 'fr'
locales['fy-NL'] = 'fy'
locales['gl'] = 'gl'
locales['gu-IN'] = 'gu'
locales['he'] = 'he'
locales['hi-IN'] = 'hi'
locales['hr'] = 'hr'
locales['hu'] = 'hu'
locales['id'] = 'id'
locales['is'] = 'is'
locales['it'] = 'it'
locales['ja'] = 'ja'
locales['kn'] = 'kn'
locales['ko'] = 'ko'
locales['lt'] = 'lt'
locales['lv'] = 'lv'
locales['nb-NO'] = 'nb'
locales['nl'] = 'nl'
locales['nn-NO'] = 'nn'
locales['pl'] = 'pl'
locales['pt-PT'] = 'pt'
locales['pt-BR'] = 'pt-br'
locales['ro'] = 'ro'
locales['ru'] = 'ru'
locales['sk'] = 'sk'
locales['sl'] = 'sl'
locales['sq'] = 'sq'
locales['sr'] = 'sr'
locales['sv-SE'] = 'sv'
locales['th'] = 'th'
locales['tr'] = 'tr'
locales['uk'] = 'uk'
locales['zh-CN'] = 'zh'

US_URL = "http://download-origin.cdn.mozilla.net/pub/firefox/releases/%s/%s/en-US/firefox-%s.tar.bz2" % (release, archi, release)
XPI_URL = "http://download-origin.cdn.mozilla.net/pub/firefox/releases/%s/%s/xpi" % (release, archi)

def get_engine_name (engines, index):
    try:
        engine = engines[index]
    except:
        return None
    if "yahoo" in engine:
        return "Yahoo"
    elif "duckduckgo" in engine:
        return "DuckDuckGo"
    elif "startpage" in engine:
        return "Startpage"
    elif "ixquick" in engine:
        return "Ixquick"
    else:
        return None

def change_value (key, value, file):
    if value is not None:
        command = "sed -i '/%(key)s=/c\%(key)s=%(value)s' %(file)s" % {'key':key, 'value':value, 'file':file}
    else:
        command = "sed -i '/%(key)s=/d' %(file)s" % {'key':key, 'file':file}
    os.system(command)

def update_json():
    with open("list.json") as json_data:
        firefox_json = json.load(json_data)
        json_data.close()

    engines = []
    for filename in sorted(os.listdir(".")):
        if filename.endswith(".xml"):
            filename = filename.replace(".xml", "")
            engines.append(filename)

    sorted_engines = []
    for priority in priorities:
        if priority in engines:
            sorted_engines.append(priority)
            engines.remove(priority)

    for engine in engines:
        sorted_engines.append(engine)

    for sublocale in firefox_json:
        firefox_json[sublocale]["visibleDefaultEngines"] = sorted_engines

    with open("list.json", "w") as json_file:
        json.dump(firefox_json, json_file)

    for sublocale in firefox_json:
        engines = firefox_json[sublocale]["visibleDefaultEngines"]
        region_properties = "../../browser-region/region.properties"
        if os.path.exists(region_properties):
            change_value("browser.search.defaultenginename", get_engine_name(engines, 0), region_properties)
            change_value("browser.search.order.1", get_engine_name(engines, 0), region_properties)
            change_value("browser.search.order.2", get_engine_name(engines, 1), region_properties)
            change_value("browser.search.order.3", get_engine_name(engines, 2), region_properties)

os.system("mkdir -p %s/debian/firefox/opt" % curdir)
os.chdir("%s/debian/firefox/opt" % curdir)
if not abort:
    os.system("wget %s" % US_URL)
    if (not os.path.exists("firefox-%s.tar.bz2" % release)):
        print "FAILED: Could not download %s" % (US_URL)
        sys.exit(1)

    os.system("bzip2 -d firefox-%s.tar.bz2" % release)
    os.system("tar xvf firefox-%s.tar" % release)
    os.system("rm firefox-%s.tar" % release)

    os.system("rm -rf firefox/defaults/pref/*")
    os.system("cp %s/pref/* firefox/defaults/pref/" % curdir)

    os.system("mkdir OMNI")
    os.system("cp firefox/browser/omni.ja OMNI/")
    os.chdir("OMNI/")
    os.system("unzip omni.ja")
    os.system("rm omni.ja")
    os.chdir("chrome/en-US/locale/browser/searchplugins/")
    os.system("rm *.xml")
    os.system("cp %s/searchplugins/en-us/* ./" % curdir)
    update_json()
    os.chdir("../../../../../")
    region_properties = "chrome/en-US/locale/browser-region/region.properties"
    if os.path.exists(region_properties):
        change_value("browser.search.defaultenginename", "Yahoo", region_properties)
        change_value("browser.search.order.1", "Yahoo", region_properties)
        change_value("browser.search.order.2", "Startpage", region_properties)
        change_value("browser.search.order.3", "DuckDuckGo", region_properties)
    os.system("zip -qr9XD omni.ja *")
    os.chdir("..")
    os.system("cp OMNI/omni.ja firefox/browser/omni.ja")
    os.system("rm -rf OMNI")

    os.system("mkdir -p %s/debian/firefox/usr/share/icons/hicolor" % curdir)
    os.chdir("%s/debian/firefox/usr/share/icons/hicolor" % curdir)
    os.system("mkdir -p 16x16/apps 32x32/apps 48x48/apps 128x128/apps")
    os.system("ln -s /opt/firefox/browser/chrome/icons/default/default16.png 16x16/apps/firefox.png")
    os.system("ln -s /opt/firefox/browser/chrome/icons/default/default32.png 32x32/apps/firefox.png")
    os.system("ln -s /opt/firefox/browser/chrome/icons/default/default48.png 48x48/apps/firefox.png")
    os.system("ln -s /opt/firefox/browser/icons/mozicon128.png 128x128/apps/firefox.png")
    os.system("mkdir -p %s/debian/firefox/opt/firefox/browser/defaults/preferences" % curdir)
    os.chdir("%s/debian/firefox/opt/firefox/browser/defaults/preferences" % curdir)
    pref_file = open("browser.js", "wb")
    pref_file.write("pref(\"extensions.autoDisableScopes\", 3);\npref(\"intl.locale.matchOS\", true);\npref(\"intl.locale.requested\", \"\");\npref(\"extensions.langpacks.signatures.required\", false);\n");
    pref_file.close()

for locale in locales:
    os.system("mkdir -p %s/debian/firefox-l10n-%s/opt/firefox/browser/extensions" % (curdir, locales[locale]))
    os.chdir("%s/debian/firefox-l10n-%s/opt/firefox/browser/extensions" % (curdir,locales[locale]))
    if not abort:
        os.system("wget %s/%s.xpi" % (XPI_URL, locale))
        if (not os.path.exists("%s.xpi" % locale)):
            print "FAILED: Could not download %s/%s.xpi" % (XPI_URL, locale)
            sys.exit(1)
        os.system("mkdir EXTENSION")
        os.system("mv ./%s.xpi ./EXTENSION/langpack-%s@firefox.mozilla.org.xpi" % (locale, locale))
        os.chdir("EXTENSION")
        os.system("unzip ./langpack-%s@firefox.mozilla.org.xpi" % locale)
        os.system("rm ./langpack-%s@firefox.mozilla.org.xpi" % locale)
        os.chdir("browser/chrome/%s/locale/browser/searchplugins" % locale)
        os.system("rm *.xml")
        os.system("cp %s/searchplugins/%s/* ./" % (curdir, locales[locale]))
        update_json()
        os.chdir("../../../../../../")
        os.system("zip -qr9XD langpack-%s@firefox.mozilla.org.xpi *" % locale)
        os.system("mv langpack-%s@firefox.mozilla.org.xpi ../" % locale)
        os.chdir("..")
        os.system("rm -rf EXTENSION")

os.chdir(curdir)
