#! /usr/local/bin/python3.9
# coding=utf-8
# --------------------------------------------------------------------
# Copyright (C) 1991 - 2019 - EDF R&D - www.code-aster.org
# This file is part of code_aster.
#
# code_aster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# code_aster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with code_aster.  If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------

"""
    %(prog)s [options]

This script has to be run after moving the installation directory of
a code_aster version. It updates the few files that need the real path of
the installation.
"""

import argparse
import os
import os.path as osp
import re
import sys


def post_install(share_aster):
    """Update files that reference the installation path.

    Arguments:
        share_aster (str): Path to the installation directory containing
            ``config.txt`` and ``profile.sh`` files.
    """
    paths = ("profile.sh", "config.txt")
    files = [osp.join(share_aster, path) for path in paths]

    newdir = osp.normpath(osp.abspath(osp.dirname(osp.dirname(share_aster))))
    previous = extract_previous(files[0])
    print("Current installation path:", newdir)
    print("Previous installation path:", previous)
    for filename in files:
        if not osp.isfile(filename):
            print("no such file:", filename)
            continue
        print("%s..." % filename)
        with open(filename, "r") as fobj:
            text = fobj.read()
        with open(filename, "w") as fobj:
            fobj.write(text.replace(previous, newdir))


def extract_previous(filename):
    """Extract the previous installation path."""
    expr = re.compile("^ASTER_DATADIR=(.*) *$", re.M)
    with open(filename, "r") as fprof:
        mat = expr.search(fprof.read())
        assert mat, "ASTER_DATADIR not defined in %s" % filename

    return osp.normpath(osp.abspath(osp.dirname(osp.dirname(mat.group(1)))))


if __name__ == '__main__':
    # command arguments parser
    parser = argparse.ArgumentParser(
        usage=__doc__,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    args = parser.parse_args()
    here = osp.normpath(osp.abspath(osp.dirname(__file__)))
    post_install(here)
    sys.exit(0)
