#!/usr/bin/env python

import os

SAGE_ROOT = os.environ['SAGE_ROOT']

location_file = '%s/local/lib/sage-current-location.txt'%SAGE_ROOT

def install_moved():
    if not os.path.exists(location_file): 
        O = open(location_file,'w')
        O.write(SAGE_ROOT)
        O.close()
        return False, ''   # first time -- so no need to update; this was during the build.

    O = open(location_file)
    R = O.read().strip()
    O.close()
    if os.path.abspath(R) != os.path.abspath(SAGE_ROOT):  # really different
        return True, R  # it moved
    return False, ''

def update_library_files(R):
    LIB = '%s/local/lib/'%os.path.abspath(SAGE_ROOT)
    # The .a files should be re-ranlib'd
    os.system('cd "%s"; ranlib *.a 1>/dev/null 2>/dev/null'%LIB)

    # The .la files hardcode path info.  Fix this.
    for F in os.listdir(LIB):
       if F[-3:] == ".la":
           G = open(LIB + F).read()
	   i = G.find('libdir=')
	   j = i+8 + G[i+8:].find("'")
	   z = G[i+8:j].strip().strip("'")
 	   i = z.rfind('local/')
	   if i != -1:
               z = z[:i]
               H = G.replace(z, os.path.abspath(SAGE_ROOT) + '/')
               open(LIB + F,'w').write(H)

def update_hardcoded_files(path):
    # The only known files with hard coded paths.
    if os.path.isdir(path):
        for X in os.listdir(path):
            update_hardcoded_files('%s/%s'%(path,X))
    else:
        P = path[-4:]
        if P == '.pyo' or P == '.pyc':
            try:
                os.unlink(path)
            except OSError, msg:
                print msg

    # Write new location file.
    if os.path.exists(location_file):
        O = open(location_file,'w')
        O.write(SAGE_ROOT)
        O.close()        

def __mysig(a,b):
    raise KeyboardInterrupt, "computation timed out because alarm was set for %s seconds"%__alarm_time

if __name__ ==  '__main__':
    # Check if SAGE has moved, and if so delete all .pyo and .pyc files
    # in the python libs directory, so they are rebuilt. 
    t, R = install_moved()
    if t:
        print "The SAGE install tree may have moved."
        print "Regenerating Python.pyo and .pyc files that hardcode the install PATH (please wait at most a few minutes)..."
        print "Please do not interrupt this."
	update_library_files(R)
        update_hardcoded_files(SAGE_ROOT + '/local/lib/python/')


