#!/usr/bin/env perl
#***********************************************************************
# This file is part of OpenMolcas.                                     *
#                                                                      *
# OpenMolcas is free software; you can redistribute it and/or modify   *
# it under the terms of the GNU Lesser General Public License, v. 2.1. *
# OpenMolcas is distributed in the hope that it will be useful, but it *
# is provided "as is" and without any express or implied warranties.   *
# For more details see the full text of the license in the file        *
# LICENSE or in <http://www.gnu.org/licenses/>.                        *
#                                                                      *
# Copyright (C) 2015, Steven Vancoillie                                *
#***********************************************************************
#
# gtags
#
# Simple wrapper to make gtags find all the source code
# in Molcas.
#
# Steven Vancoillie, June 2015

use File::Basename;

my $MOLCAS_DRIVER;
$MOLCAS_DRIVER = $ENV{"MOLCAS_DRIVER"} or $MOLCAS_DRIVER = "molcas";
my $DRIVER_base = basename($MOLCAS_DRIVER);

my $MOLCAS=$ENV{"MOLCAS"};
die "MOLCAS not set, set it or use command \"$DRIVER_base gtags\"\n" unless ($MOLCAS);

# check if gtags exists in our path
my $gtags_exists = 0;
foreach my $path (split /:/, $ENV{'PATH'}) {
    if ( -f "$path/gtags" && -x _ ) {
        $gtags_exists = 1;
        last;
    }
}
if (not $gtags_exists) {
    print "Error: gtags not available\n";
    exit 1;
}

# gtags needs a minimal configuration file to work with ctags
my $HOME = $ENV{"HOME"};
my $MOLCAS_CONF_DIR = "$HOME/.Molcas";
if (! -d $MOLCAS_CONF_DIR) {
    mkdir($MOLCAS_CONF_DIR)
        or die "cannot create $MOLCAS_CONF_DIR: $!";
}

my $gtags_conf = "$MOLCAS_CONF_DIR/gtags.conf";
if (! -f $gtags_conf) {
    open(GTAGS_CONF, ">", $gtags_conf)
        or die "cannot open $gtags_conf: $!";
    print GTAGS_CONF <<'EOF';
#gtags configuration for Molcas
default:\
    :langmap=C\:.c.h:\
    :langmap=Fortran\:.f.f90.inc.fh:\
    :gtags_parser=C\:/usr/lib/gtags/exuberant-ctags.so:\
    :gtags_parser=Fortran\:/usr/lib/gtags/exuberant-ctags.so:\
EOF
    close(GTAGS_CONF)
}

# run gtags command
print "running gtags...";
system("gtags --gtagsconf $gtags_conf");
print "done\n";

exit 0;
