#!/usr/bin/env python

from __future__ import print_function

import glob
import os
import sys

SAGE_ROOT     = os.path.realpath(os.environ['SAGE_ROOT'])
SAGE_LOCAL    = os.environ['SAGE_LOCAL']

location_file = os.path.join(SAGE_LOCAL, 'lib', 'sage-current-location.txt')
force_file    = os.path.join(SAGE_LOCAL, 'lib', 'sage-force-relocate.txt')


def write_location_file():
    """
    Write the location file with the current value of ``SAGE_ROOT``.
    """
    O = open(location_file, 'w')
    O.write(SAGE_ROOT)
    O.close()


def read_location_file():
    """
    If the location file exists, return the path contained in it.
    Otherwise return ``None``.
    """
    try:
        f = open(location_file)
    except IOError:
        return None
    path = f.read().strip()
    f.close()
    # Make the path absolute, even though this should not be needed.
    return os.path.abspath(path)


def write_config_files():
    """
    Write various configuration files which contain the ``SAGE_ROOT``
    path.
    """
    # Currently only one file (for the experimental package qepcad):
    # $SAGE_LOCAL/default.qepcadrc
    f = open(os.path.join(SAGE_LOCAL, 'default.qepcadrc'), 'w')
    text = \
"""# THIS FILE IS AUTOMATICALLY GENERATED by sage-location -- DO NOT EDIT

#####################################################
# QEPCAD rc file.
# This file allows for some customization of QEPCAD.
# Right now, the ability to give a path to Singular,
# so that it gets used for some computer algebra
# computations is the only feature.
#####################################################
SINGULAR %s
""" % os.path.join(SAGE_LOCAL, 'bin')

    f.write(text)
    f.close()


def sage_relocate():
    """
    High-level function which calls various functions to handle
    relocation.  To be called either for the initial install or when
    the Sage tree has moved.

    These operations should all be idempotent: executing them more than
    once should be equivalent to executing them once.
    """
    write_config_files()

    # Write the new location file as last thing in this script,
    # so that it only gets written if there were no exceptions.
    write_location_file()


RELOCATION_ERROR = """
ERROR:  The Sage installation tree has moved

from {OLD_SAGE_ROOT}
  to {SAGE_ROOT}

This is not supported, and Sage will not work. To install Sage from a
binary package:

1. Open the .tar.bz2 archive (or .dmg on OSX)

2. Move the SageMath folder/app to where you want it to be. You can
   also rename the directory now.

3. Start sage for the first time. This will then automatically patch
   paths in binaries.

After starting Sage for the first time you cannot change the
installation any more. To install Sage elsewhere, start over from the
binary package. Or recompile Sage from scratch in the new location
("make distclean && make")
"""


if __name__ == '__main__':

    if SAGE_ROOT is None:
        print('You must run this script from within a Sage shell')
        sys.exit(1)

    # Previous SAGE_ROOT, read from "sage-location.txt".
    # OLD_SAGE_ROOT is None if this is a first-time install.
    OLD_SAGE_ROOT = read_location_file()

    # If the force file exists (test that by deleting it),
    # then always run sage_locate().
    try:
        os.unlink(force_file)
        force_relocate = True
    except OSError:
        force_relocate = False

    if OLD_SAGE_ROOT != SAGE_ROOT or force_relocate:
        if OLD_SAGE_ROOT is None:
            print("This looks like the first time you are running Sage.")
        elif OLD_SAGE_ROOT != SAGE_ROOT:
            print(RELOCATION_ERROR.format(OLD_SAGE_ROOT=OLD_SAGE_ROOT, SAGE_ROOT=SAGE_ROOT))
            sys.exit(1)
        elif force_relocate:
            print("Forcing sage-location, probably because a new package was installed.")
        else:
            print("The Sage installation tree has moved")
            print("from %s" % OLD_SAGE_ROOT)
            print("  to %s" % SAGE_ROOT)
            assert(False)
        print("Cleaning up, do not interrupt this.")
        sys.stdout.flush() # One never knows...

        sage_relocate()
        print("Done cleaning.")
