#!usr/bin/env python
import os, sys
import fileinput

if len(sys.argv) != 2:
    print "Usage: install_locale.py [path_to_locale|URL]"
    sys.exit(1)
if not os.access("/usr/lib/locale/", os.W_OK):
    print "Error: You should run this command as root (or with sudo)"
    sys.exit(1)

locale_file = sys.argv[1]
locale = locale_file.rsplit('/', 1)[-1].split('.', 1)[0]
supported_file = '/usr/share/i18n/SUPPORTED'

def add_locale_to_supported(locale):
    """ Add locale to supported locale list """
    is_already = False
    for line in fileinput.input(supported_file, inplace=1):
        if not is_already:
            if line.startswith(locale):
                is_already = True
            elif line > locale:
                print "%s.UTF-8 UTF-8" % locale
                is_already = True
        print line,

if locale_file.startswith("http"):
    import urllib2
    u = urllib2.urlopen(locale_file)
    loc_file = open(locale, 'w')
    loc_file.write(u.read())
    loc_file.close()
    locale_file = os.path.abspath(loc_file.name)

cmd = "localedef -i %(locale_file)s --charmap=UTF-8 %(locale)s.UTF-8" % locals()
res = os.system(cmd)
if res == 0:
    print "%s locale successfully installed on your system" % locale

# Try to add locale to SUPPORTED
if not os.path.exists(supported_file):
    print "We don't know where is the SUPPORTED file on your system. Skipping..."
else:
    add_locale_to_supported(locale)

