#!/usr/bin/env python

import os, sys, shutil, py_compile, os.path

bins = ['img2db', 'dbpass']
libs = ['xmlrpclib_auth.py', 'xmlrpclib.py', 'FtpServer.py',
        'ScanOption.py', 'Util.py', 'Img2dbServer.py',
        'Record.py', 'Log.py']
others = ['source_img2db']

def get_newpath():
    homebin = os.environ['HOME'] + '/bin'
    path = os.environ['PATH']
    newpath = None
    if path.find(homebin) > 0:
        newpath = None
    else:
        newpath = homebin + ":$PATH"
    return newpath

def get_pythonpath():
    img2dbpath = os.environ['HOME'] + "/lib/img2db"
    if os.environ.has_key('PYTHONPATH'):
        pypath = os.environ['PYTHONPATH']
        if pypath.find('img2db') > 0:
            pypath = None
        else:
            pypath = img2dbpath + ":$PYTHONPATH"
    else:
        pypath = img2dbpath
    return pypath


def generate_source():
    shell = os.environ['SHELL']
    sourcefile = "source_img2db"
    sfile = open(sourcefile, "w")
    newpath = get_newpath()
    pypath = get_pythonpath()
    home = os.environ['HOME']
    
    if shell == '/bin/csh' or shell == '/bin/tcsh':
        if newpath:
            sfile.write("setenv PATH " + newpath + "\n")
        if pypath:
            sfile.write("setenv PYTHONPATH " + pypath + "\n")

        if shell == '/bin/tcsh' and os.path.exists(home + "/.tcshrc"):
            shellrc = home + "/.tcshrc"
        else:
            shellrc = home + "/.cshrc"
    elif shell == '/bin/bash' or shell == '/bin/zsh':
        if newpath:
            sfile.write("export PATH=\"" + newpath + "\"\n")
        if pypath:
            sfile.write("export PYTHONPATH=\"" + pypath + "\"\n")

        if shell == "/bin/zsh" and os.path.exists(home + "/.zshrc"):
            shellrc = home + "/.zshrc"
        else:
            shellrc = home + "/.bashrc"

    sfile.close()

    if os.path.getsize(sourcefile) > 0:
        print "\nPlease add the following line to the end of your " + shellrc
        print "\nsource $HOME/lib/img2db/source_img2db\n"
        

def copy_files(is_root):
    global bins
    global libs
    user = os.environ['USER']
    
    if is_root:
        bindir = "/usr/local/bin"
        pyver = str(sys.version_info[:2][0]) + "." + str(sys.version_info[:2][1])
        pylibdir = sys.exec_prefix + "/lib/python" + pyver + "/site-packages"
        libdir = pylibdir + "/img2db"
        try:
            shutil.copy('img2db.pth', pylibdir)
        except IOError:
            print "Error: you need root permission to do this."
            return 1
    else:
        installdir = os.environ['HOME']
        bindir = installdir + "/bin"
        libdir = installdir + "/lib/img2db"
    
    try:
        os.makedirs(bindir)
    except:
        pass
    
    for bin in bins:
        shutil.copy(bin, bindir)    

    try:
        os.makedirs(libdir)
    except:
        pass
    
    for pyfile in libs:
        shutil.copy(pyfile, libdir)

    if not is_root:
        for file in others:
            shutil.copy(file, libdir)

    for pyfile in libs:
        abspy = os.path.join(libdir, pyfile)
        py_compile.compile(abspy)
        
    
def main():
    if os.name == 'nt':
        return

    if len(sys.argv) > 2:
        print '\nusage: setup [root]\n'
        sys.exit(1)

    if len(sys.argv) == 2 and sys.argv[1] == 'root':
        is_root = 1
    else:
        is_root = 0

    generate_source()
    copy_files(is_root)

if __name__ == '__main__':
    main()
    
