#################################################################
#                                                               #
# Copyright (c) 2010-2021 Fidelity National Information		#
# Services, Inc. and/or its subsidiaries. All rights reserved.	#
#                                                               #
#       This source code contains the intellectual property     #
#       of its copyright holder(s), and is made available       #
#       under a license.  If you do not know the terms of       #
#       the license, please stop and do not read further.       #
#                                                               #
#################################################################
# Usage: source "/usr/lib/x86_64-linux-gnu/fis-gtm/V7.1-008_x86_64"/gtmprofile
# Sets up environment for single-user use of GT.M with reasonable defaults.
# Explicitly specify gtm_chset=UTF-8 before running this for UTF-8 mode.
# Explicitly specify the gtmdir=directory before sourcing this for simple multi-user environments.
# System administrators should adapt as appropriate for more complex multi-user and production environments.

# Expects the following environment variables to be set:
#   $gtm_chset - set to "UTF-8" if GT.M is to run in UTF8 mode
#   $gtm_passwd and $gtm_dbkeys if database encryption is used
# Attempts to set the following environment variables to reasonable values:
#   $gtm_dist $gtmgbldir $gtm_icu_version $gtm_log $gtm_principal_editing $gtm_prompt $gtm_retention $gtmroutines $gtm_tmp $gtmver
# The following shell variables are used and left unset:
#   $old_gtm_dist $old_gtmroutines $old_gtmver $tmp_gtm_shlib $tmp_gtm_tmp $tmp_passwd
# The following shell variables are used and left set:
#   $arch
# ; is used as a separator for sed as being the character most unlikely to be in file names

# Set gtm_arch - GT.M installation script sets the actual architecture & shared library extension for use in this script
arch="linux"

# Save gtmroutines if it exists because we need to temporarily override it
if [ -n "$gtmroutines" ] ; then
    old_gtmroutines="$gtmroutines"
else
    unset old_gtmroutines
fi

# Save gtm_passwd if defined because we don't want to mess with prompting for a password within this script
# Need to distinguish between $gtm_passwd not set at all vs. set to null string
if [ -z "${gtm_passwd+isset}" ] ; then
    unset tmp_passwd
else
    tmp_passwd=$gtm_passwd ; unset gtm_passwd
fi

# If an existing GT.M is defined in $gtm_dist, capture it to change version number & directory in environment variables
# Since %XCMD is new, cannot assume that old GT.M version has it
if [ -n "$gtm_dist" ] ; then
    old_gtm_dist=$gtm_dist
    if [ -f $gtm_dist/_XCMD.m ] ; then
	tmp_gtm_shlib=`basename $gtm_dist/libgtmshr.* | cut -d . -f 2` ; export tmp_gtm_shlib
	if [ -f "$gtm_dist/libgtmutil.$tmp_gtm_shlib" ] ; then gtmroutines="$gtm_dist/libgtmutil.$tmp_gtm_shlib"
	else gtmroutines=$gtm_dist ; fi
	export gtmroutines
        old_gtmver=`$gtm_dist/mumps -run %XCMD 'Write $Piece($ZVersion," ",2),"_",$Piece($ZVersion," ",4)'`
    else
        unset old_gtmver
    fi
else unset old_gtm_dist old_gtmver
fi

# Set gtm_dist - GT.M installation script sets the actual directory name
gtm_dist="/usr/lib/x86_64-linux-gnu/fis-gtm/V7.1-008_x86_64" ; export gtm_dist

# Determine name of shared library file name extension on this platform
tmp_gtm_shlib=`basename $gtm_dist/libgtmshr.* | cut -d . -f 2` ; export tmp_gtm_shlib

# Idempotence says change the environment only if a new GT.M directory is being pointed to
# otherwise just restore $gtmroutines and exit
if [ $gtm_dist != "$old_gtm_dist" ] ; then

    # Force $gtmroutines to guarantee access to %XCMD for now; repaired later
    if [ -f "$gtm_dist/libgtmutil.$tmp_gtm_shlib" ] ; then gtmroutines="$gtm_dist/libgtmutil.$tmp_gtm_shlib $gtm_dist"
    else gtmroutines=$gtm_dist ; fi
    export gtmroutines
    # Set $gtm_icu_version - should be set before checking for UTF-8 mode
    if [ -z "$gtm_icu_version" ] ; then
	if [ -x "$(command -v pkg-config)" -a $(pkg-config --exists icu-io; echo $?) -eq 0 ]; then
		versioncmd="pkg-config --modversion icu-io"
		libcmd="pkg-config --variable=libdir icu-io"
	elif [ -x "$(command -v icu-config)" ] ; then
		versioncmd="icu-config --version"
		libcmd="icu-config --libdir"
	elif [ -x "$(command -v pkg-config)" -a $(pkg-config --exists icu; echo $?) -eq 0 ]; then
		versioncmd="pkg-config --modversion icu"
		libcmd="pkg-config --variable=libdir icu"
	fi
	if [ -n "$versioncmd" ]; then
		gtm_icu_version=`$versioncmd | gtm_chset=M $gtm_dist/mumps -run %XCMD 'Read x Write $FNumber(x*$Select(+x>5:.1,1:1),"",1)'`
		extendlibpath=`$libcmd`
		export gtm_icu_version
		# Add library path to LD_LIBRARY_PATH
		if [ "" = "$LD_LIBRARY_PATH" ]; then LD_LIBRARY_PATH="$extendlibpath"; else LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$extendlibpath";fi; export LD_LIBRARY_PATH
		if [ "ibm" = "$arch" ]; then
			if [ "" = "$LIBPATH" ]; then LIBPATH="$extendlibpath"; else LIBPATH="$LIBPATH:$extendlibpath";fi; export LIBPATH;
			unset gtm_icu_version
		fi
	fi
    fi

    # If UTF-8 is selected, and UTF-8 mode works, set $gtm_dist to utf8 subdirectory
    # Note that if UTF-8 mode cannot be properly set, GT.M remains configured for M mode
    # default $LC_CTYPE if not set
    # depending on the list of locales configured, locale -a might be considered a binary output.
    # grep needs -a option to process the output as text but -a is not supported on the non-linux servers we have.
    os=`uname -s`
    if [ $os = "Linux" ]; then
    	binaryopt="-a"
    else
    	binaryopt=""
    fi
    if [ "`echo $gtm_chset|tr utf UTF`" = "UTF-8"  ] ; then
	if [ ! -d $gtm_dist/utf8 ] ; then
		echo "$gtm_dist/utf8 does not exist. Re-install GT.M with UTF-8 support to proceed."
		echo "Alternatively, unset gtm_chset environment variable to run gtmprofile without UTF-8 support."
		return 1
	fi
	if [ -z "$LC_CTYPE" ] ; then
		LC_CTYPE=`locale -a | grep $binaryopt -iE '\.utf.?8$' | head -n1` ; export LC_CTYPE
		echo $LC_CTYPE | grep -iq .utf
		if [ $? -ne 0 ] ; then
			echo "No UTF-8 locales available. Please install a UTF-8 locale to proceed."
			echo "Alternatively, unset gtm_chset environment variable to run gtmprofile without UTF-8 support."
			return 1
		fi
	else
		echo $LC_CTYPE | grep -iq .utf
		if [ $? -ne 0 ] ; then
			echo "LC_CTYPE=C is set to a non-UTF-8 locale. Set the environment variable LC_CTYPE or LC_ALL to any valid UTF-8 locale."
			echo "Alternatively, unset LC_CTYPE so that gtmprofile can automatically set it to an available UTF-8 locale."
			return 1
		fi
	fi
	if [ "`echo Halt | gtm_prompt='GTM>' $gtm_dist/utf8/mumps -dir | tail -n 1`" = 'GTM>' ] ; then
		gtm_dist=$gtm_dist/utf8
		if [ -f "$gtm_dist/libgtmutil.$tmp_gtm_shlib" ] ; then
			gtmroutines="$gtm_dist/libgtmutil.$tmp_gtm_shlib $gtm_dist"
		else gtmroutines=$gtm_dist ; fi
	else
		echo "Error while executing $gtm_dist/utf8/mumps -dir. Cannot set gtm_dist and gtmroutines to $gtm_dist/utf8."
		echo HALT | $gtm_dist/utf8/mumps -dir
		return 1
	fi
    fi

    # Set $gtmver - must be set before $gtmroutines and $gtm_prompt are set
    gtmver=`$gtm_dist/mumps -run %XCMD 'Write $Piece($ZVersion," ",2),"_",$Piece($ZVersion," ",4)'` ; export gtmver

    # Set $gtm_prompt - must be set after checking for UTF-8 mode since prompt may be based on gtm_dist
    if [ -z "$gtm_prompt" ] ; then
        gtm_prompt="GTM>"
    else
        if [ -n "$old_gtm_dist" ] ; then
            gtm_prompt=`echo $gtm_prompt | sed "s;$old_gtm_dist;$gtm_dist;"`
        fi
        if [ -n "$old_gtmver" ] ; then
            gtm_prompt=`echo $gtm_prompt | sed "s;$old_gtmver;$gtmver;"`
        fi
    fi
    export gtm_prompt

    # Set $gtmdir and create default directories if they don't exist
    if [ -n "$gtmdir" ] ; then
        if [ -n "$old_gtm_dist" ] ; then
            gtmdir=`echo $gtmdir | sed "s;$old_gtm_dist;$gtm_dist;"`
        fi
        if [ -n "$old_gtmver" ] ; then
            gtmdir=`echo $gtmdir | sed "s;$old_gtmver;$gtmver;"`
        fi
    else
        gtmdir=$HOME/.fis-gtm
    fi
    export gtmdir
    mkdir -p $gtmdir/r $gtmdir/$gtmver/g $gtmdir/$gtmver/o $gtmdir/$gtmver/r $gtmdir/$gtmver/o/utf8

    # Set $gtmroutines - edit for new GT.M if previously set, otherwise use default
    if [ -n "$old_gtmroutines" ] ; then
        gtmroutines="$old_gtmroutines"
        if [ -n "$old_gtm_dist" ] ; then
            gtmroutines=`echo $gtmroutines | sed "s;$old_gtm_dist;$gtm_dist;"`
        fi
        if [ -n "$old_gtmver" ] ; then
            gtmroutines=`echo $gtmroutines | sed "s;$old_gtmver;$gtmver;"`
        fi
    else
	if [ -f "$gtm_dist/libgtmutil.$tmp_gtm_shlib" ] ; then gtmroutines="$gtm_dist/libgtmutil.$tmp_gtm_shlib $gtm_dist"
	else gtmroutines=$gtm_dist ; fi
        if [ "utf8" = `basename $gtm_dist` ] ; then
	    if [ -d $gtm_dist/plugin/o/utf8 ] ; then
		gtmroutines=`$gtm_dist/mumps -run %XCMD 'set x=$ztrnlnm("gtm_dist")_"/plugin/o/utf8/*."_$ztrnlnm("tmp_gtm_shlib") for  set y=$zsearch(x) quit:""=y  write y," "'`"$gtm_dist/plugin/o/utf8($gtm_dist/plugin/r) $gtmroutines"
	    fi
            gtmroutines=`$gtm_dist/mumps -run %XCMD 'set x=$ztrnlnm("gtmdir")_"/"_$ztrnlnm("gtmver")_"/o/utf8/*."_$ztrnlnm("tmp_gtm_shlib") for  set y=$zsearch(x)  quit:""=y  write y," "'`"$gtmdir/$gtmver/o/utf8($gtmdir/$gtmver/r $gtmdir/r) $gtmroutines"
	else
	    if [ -d $gtm_dist/plugin/o ] ; then
		gtmroutines=`$gtm_dist/mumps -run %XCMD 'set x=$ztrnlnm("gtm_dist")_"/plugin/o/*."_$ztrnlnm("tmp_gtm_shlib") for  set y=$zsearch(x) quit:""=y  write y," "'`"$gtm_dist/plugin/o($gtm_dist/plugin/r) $gtmroutines"
	    fi
            gtmroutines=`$gtm_dist/mumps -run %XCMD 'set x=$ztrnlnm("gtmdir")_"/"_$ztrnlnm("gtmver")_"/o/*."_$ztrnlnm("tmp_gtm_shlib") for  set y=$zsearch(x)  quit:""=y  write y," "'`"$gtmdir/$gtmver/o($gtmdir/$gtmver/r $gtmdir/r) $gtmroutines"
	fi
    fi
    export gtmroutines

    # Set $gtmgbldir - edit for new GT.M if previously set, otherwise use default and create if needed
    if [ -n "$gtmgbldir" ] ; then
        if [ -n "$old_gtm_dist" ] ; then
            gtmgbldir=`echo $gtmgbldir | sed "s;$old_gtm_dist;$gtm_dist;"`
        fi
        if [ -n "$old_gtmver" ] ; then
            gtmgbldir=`echo $gtmgbldir | sed "s;$old_gtmver;$gtmver;"`
        fi
    else
        gtmgbldir=$gtmdir/$gtmver/g/gtm.gld
    fi
    export gtmgbldir

    # Set $gtm_tmp
    tmp_gtm_tmp=`uname -s`
    if [ "HP-UX" = $tmp_gtm_tmp -o "SunOS" = $tmp_gtm_tmp ] ; then
        tmp_gtm_tmp=/var/tmp/fis-gtm
    else
        tmp_gtm_tmp=/tmp/fis-gtm
    fi
    if [ ! -d "$tmp_gtm_tmp" ] ; then
    	mkdir $tmp_gtm_tmp ; chmod a+rw,+t $tmp_gtm_tmp
    fi
    tmp_gtm_tmp=$tmp_gtm_tmp/$gtmver
    if [ -d "$tmp_gtm_tmp" ] ; then
        gtm_tmp=$tmp_gtm_tmp
    else
        if [ -n "$old_gtm_dist" ] ; then
            gtm_tmp=`echo $gtm_tmp | sed "s;$old_gtm_dist;$gtm_dist;"`
        fi
        if [ -n "$old_gtmver" ] ; then
            gtm_tmp=`echo $gtm_tmp | sed "s;$old_gtmver;$gtmver;"`
        fi
        if [ ! -d "$gtm_tmp" ] ; then
            mkdir -p $tmp_gtm_tmp ; chmod a+rw,+t $tmp_gtm_tmp ; gtm_tmp=$tmp_gtm_tmp
        fi
    fi
    export gtm_tmp

    # Set $gtm_log - use recommended directory if it exists, otherwise modify old value if it exists
    # Don't need to worry about non-existent directory because gtmsecshr will create it
    # $gtm_tmp will be used if $gtm_log not defined
    if [ -d /var/log/fis-gtm/$gtmver ] ; then
        gtm_log=/var/log/fis-gtm/$gtmver
    elif [ -n "$gtm_log" ] ; then
        if [ -n "$old_gtm_dist" ] ; then
            gtm_log=`echo $gtm_log | sed "s;$old_gtm_dist;$gtm_dist;"`
        fi
        if [ -n "$old_gtmver" ] ; then
            gtm_log=`echo $gtm_log | sed "s;$old_gtmver;$gtmver;"`
        fi
    else
        gtm_log=$gtm_tmp
    fi
    export gtm_log

    # Set $PATH
    if [ -n "$old_gtm_dist" ] ; then
        PATH=`echo $PATH | sed "s;$old_gtm_dist;$gtm_dist;"`
    fi
    if [ -n "$old_gtmver" ] ; then
        PATH=`echo $PATH | sed "s;$old_gtmver;$gtmver;"`
    fi
    if [ -z "`echo $PATH | grep -E  \(:\|\^\)$gtm_dist\(:\|$\)`" ] ; then
        PATH=$PATH:$gtm_dist
    fi

    # Other useful environment variables
    # System administrators - add, delete or modify GT.M environment variables here as appropriate for your installation
    if [ -z "$gtm_etrap" ] ; then
        gtm_etrap='Write:(0=$STACK) "Error occurred: ",$ZStatus,!' ; export gtm_etrap
    fi
    if [ -z "$gtm_principal_editing" ] ; then
        gtm_principal_editing="EDITING" ; export gtm_principal_editing
    fi
    if [ -z "$gtm_repl_instance" ] ; then
        gtm_repl_instance=$gtmdir/$gtmver/g/gtm.repl ; export gtm_repl_instance
    elif [ -n "$old_gtmver" ] ; then
	gtm_repl_instance=`echo $gtm_repl_instance | sed "s;$old_gtmver;$gtmver;"`
    fi
    if [ -z "$gtm_retention" ] ; then
        gtm_retention=42 ; export gtm_retention
    fi
    # Set & uncomment these as required
    # Refer to the GT.M Administration & Operations Guide for complete list of GT.M environment variables
    # export gtm_autorelink_keeprtn=1	# leave auto-relinked object code in the shared memory repositories
    # export gtm_linktmpdir=    	# put relinkctl files in location other than $gtm_tmp
    # export gtm_baktmpdir=		# location for MUPIP BACKUP temporary snapshot files
    # export gtm_snaptmpdir=		# location for MUPIP INTEG temporary snapshot files

    # Set environment variables for plugins in $gtm_dist/plugin
    tmp_gtm_tmp=`uname -s`
    if [ "HP-UX" = $tmp_gtm_tmp -o "SunOS" = $tmp_gtm_tmp ] ; then
        tmp_gtm_tmp=/var/tmp/
    else
        tmp_gtm_tmp=/tmp/
    fi
    tmp_gtm_tmp=$tmp_gtm_tmp`$gtm_dist/mumps -run %XCMD 'write $$%RANDSTR^%RANDSTR(12)'`.tmp
    $gtm_dist/mumps -run %XCMD 'set x=$ztrnlnm("gtm_dist")_"/plugin/*.xc" for  set y=$zsearch(x,213) quit:""=y  set z=$zparse(y,"NAME") write "GTMXC_",z,"=",y," ; export GTMXC_",z,!' >$tmp_gtm_tmp
    if [ -s $tmp_gtm_tmp ] ; then . $tmp_gtm_tmp ; fi
    rm $tmp_gtm_tmp

    # Define aliases
    alias dse="$gtm_dist/dse"
    alias gde="$gtm_dist/mumps -run GDE"
    alias gtm="$gtm_dist/gtm"
    alias lke="$gtm_dist/lke"
    alias mupip="$gtm_dist/mupip"

    # Create default global directory and database if they don't exist
    # Must handle case where database file path is relative to global directory
    if [ ! -f $gtmgbldir ] ; then
        if [ -f $gtm_dist/gdedefaults ] ; then
            $gtm_dist/mumps -run %XCMD 'Write "@","'$gtm_dist'/gdedefaults",!,"exit",!' | $gtm_dist/mumps -run GDE; stty sane
        else
            echo exit | $gtm_dist/mumps -run GDE
        fi
    fi
    if [ ! -f "`dirname $gtmgbldir`/`basename $gtmgbldir gld`dat" ] ; then
        ( cd `dirname $gtmgbldir` ; mupip create ; mupip set -journal="on,before" -region "*" )
    fi

# If $old_gtm_dist and $gtm_dist are the same, need to restore $gtmroutines
else
    gtmroutines="$old_gtmroutines" ; export gtmroutines
fi

# Restore gtm_passwd if it was set
if [ ! -z "${tmp_passwd+isset}" ] ; then
    gtm_passwd=$tmp_passwd ; export gtm_passwd
fi

unset old_gtm_dist old_gtmver old_gtmroutines tmp_gtm_shlib tmp_gtm_tmp tmp_passwd
