import os, sys

install_path = "C:\\PROGRA~1\\CHUNKIE"

try:
    import pythoncom, win32api, win32con
except:
    print "Error: could not load one of the Windows-specific libraries.\n"\
            "Please install the win32all package first!"
    raw_input()
    sys.exit()

raw_input("""
The Chunkie Installer for Windows.

Chunkie (c) Guido Wesdorp 2002.
This program is subject to the General Public License.
A copy of this license can be found in the same directory
or package as this installer, on http://johnnydebris.net
or on http://www.gnu.org.

Press enter to continue...
""")

# install_path MUST BE ABSOLUTE!!
install_path = "C:\\PROGRA~1\\CHUNKIE"

try:
    print "Creating directories"
    if not os.path.isdir(install_path):
        try:
            os.mkdir(install_path)
        except:
            print "Error creating directory " + install_path + ": " + str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1])
            sys.exit()
    
    if not os.path.isdir(install_path + "\\Chunks"):
        try:
            os.mkdir(install_path + "\\Chunks")
        except:
            print "Error creating directory " + install_path + "\\Chunks: " + str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1])
            sys.exit()
    
    print "Copying and modifying files"

    guid = pythoncom.CreateGuid()
    file = open("chunkie.py", "r").read()
    file = file.replace("[__TMPDIR__]", '%s\\Chunks' % install_path)
    file = file.replace("[__CLASSID__]", str(guid))
    
    open(install_path + "\\chunkie.py", "w").write(file)
    open(install_path + "\\activechunkie.htm", "w").write(open("activechunkie.htm").read())
    
    print "Adding registry-entries"
    rkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, "Software\\Microsoft\\Internet Explorer\\MenuExt\\Download with &Chunkie")
    win32api.RegSetValue(rkey, None, win32con.REG_SZ, install_path + "\\activechunkie.htm")
    win32api.RegSetValueEx(rkey, "contexts", 0, win32con.REG_DWORD, 34)
    
    print "Registering Chunkie as COM-server"
    os.chdir(install_path)
    answer = raw_input("Enter 'y' to register the server. Note: the Python install-directory\n"\
                "MUST be added to your path. If you do not have that, you can register\n"\
                "the server by running it from the command-line with the argument 'register'\n")
    if answer == 'y':
        os.system("python c:\\progra~1\\chunkie\\chunkie.py register")
    
    raw_input("Finished!")
except:
    raw_input("Exception: " + str(sys.exc_info()[0]) + ": " + str(sys.exc_info()[1]))

