#!/usr/bin/env sage-python

# This script is executed by $SAGE_LOCAL/bin/sage
# before starting sage.

from __future__ import print_function

import os
import sys

SAGE_ROOT     = os.environ.get('SAGE_ROOT', None)
if SAGE_ROOT:
   SAGE_ROOT = os.path.realpath(SAGE_ROOT)
SAGE_LOCAL    = os.environ['SAGE_LOCAL']

location_file = os.path.join(SAGE_LOCAL, 'lib', 'sage-current-location.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.
    """


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:
        # In situations without SAGE_ROOT, relocation is a no-op.
        sys.exit(0)

    # 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 OLD_SAGE_ROOT is None:
        sage_relocate()
    elif not os.path.samefile(OLD_SAGE_ROOT, SAGE_ROOT):
        print(RELOCATION_ERROR.format(OLD_SAGE_ROOT=OLD_SAGE_ROOT, SAGE_ROOT=SAGE_ROOT))
        sys.exit(1)
