#!/bin/bash

# **************************** LICENSE START ***********************************
#
# Copyright 2019 ECMWF and INPE. This software is distributed under the terms
# of the Apache License version 2.0. In applying this license, ECMWF does not
# waive the privileges and immunities granted to it by virtue of its status as
# an Intergovernmental Organization or submit itself to any jurisdiction.
#
# ***************************** LICENSE END ************************************

#
# DO NOT EDIT! SCRIPT PRODUCED BY make IN DIR ./scripts!
#
set -ea
#
# THIS FILE IS GENERATED BY cmake on 2025.05.25
#
WMO_SITE_NR=255
##QT_DIR_LIB=/usr/local/apps/qt/4.6.2-64/lib
ARCH=`dpkg-architecture -qDEB_HOST_MULTIARCH`
METVIEW_BIN=/usr/lib/$ARCH/metview
PATH=::${PATH}
INSTALLDIR=/usr/share/metview
METVIEW_SCRIPT=metview
MV_MARS_ACCESS=MARS_webapi
MARS_HOME=${METVIEW_MARS_HOME:=}
METVIEW_DIR_DEV=/usr/share/metview
METVIEW_TITLE_PROD="Production "
METVIEW_TITLE_DEV="Development "
MV_ENVIRON=common
MV_USAGE_LOG=OFF
MV_LOG_DIR=
##OS=linux
##MAJOR_VERSION=2
SHELL=/bin/sh
MAGPLUS_HOME=/usr
GRIBAPI_DIR=/usr/.
##MV_PYTHON_COMMAND=/usr/local/bin/python
MV_ODB1_VERSION=

##MV_ODB1_BIN=/usr/local/apps/odb/CY37R3.001/pgf90/LP64/bin
##MV_ODB1_USE_SCRIPT=/usr/local/share/ecmwf/use/sh.odb
METVIEW_RELEASE=5.23.1
METVIEW_VERSION_TITLE="Metview 5.23.1  (2025.05.25)"
METVIEW_GUI_BUILT=true
MV_FLEXTRA_EXE=/usr/bin/flextra



MV_WEATHER_ROOM_BUILT=false
MV_BUNDLE_CONTAINS_METVIEW=x1
MV_BUNDLE_CONTAINS_MAGICS=x
MV_BUNDLE_CONTAINS_EMOSLIB=x
MV_BUNDLE_CONTAINS_ECCODES=x

MV_BUNDLE_SRC=/build/metview
METVIEW_QT5=
MV_MIR=1

# store for later in case the mars env script resets it
MV_ECCODES_DEBUG=${ECCODES_DEBUG:=""}


MV_NETWORK_PROXY=NO

# prevent environment variable disruptions caused by scripts
# that are called from $BASH_ENV. We have seen a case where having
# default modules set (with the 'module initadd' command) can cause
# those modules to be loaded with each shell that Metview spawns,
# overwriting MAGPLUS_HOME for example. See JIRA issue METV-1406.
unset BASH_ENV





# on some systems, the locale is set in such a way that dots and commas within numbers
# are 'the other way around' compared with what we expect; we can override this
# without affecting the other aspects of the locale by just setting LC_NUMERIC
# to "C", which should work on all systems. This setting is supposed to provide
# a 'machine-friendly' locale and does not reply on a specific one such as en_GB.UTF-8.
LC_NUMERIC="C"


# on an increasing number of systems, it is necessary to set this env var,
# so we now set it to 1 by default. Users can set it to 0 to disable it.
METVIEW_LOCALHOST=${METVIEW_LOCALHOST:=1}

#
# Metview scripts are built automatically by 'make'.
#
# NOTE: two external files for customising, they are executed
#       only if they exist ($MV_ENVIRON):
#   - 'metview_local.$MV_ENVIRON' (for pre-stuff i.e. to set site dep values)
#   - 'metview_stat' collects usage statistics (for ECMWF)
#   - 'metview_local2.$MV_ENVIRON' (after flags process, e.g. batch/interactive)
#-----------------------------------------------------------

# abort if using unset env.vars
# no, because this one causes problems with ksh users (.kshrc)
#set -o nounset

# ===========================================================
#                      f u n c t i o n s
# ===========================================================

#checkvar() {
#	n=$1
#	n=`eval echo \\$$n`
#	if [ "$n" = "" ]
#	then
#		echo $me: Variable $1 is not defined. Cannot continue 1>&2
#		exit 1
#	fi
#	#-- if supposed to be a directory then check if exists
#	if [ X$2 = Xdir ]
#	then
#		[ -d $n ] || echo $me: Warning! $1 points to non-existing $n 1>&2
#	fi
#}

# -------------------------------------------------------------
# File to pass info from script to MetviewUI message window

info(){
	if [ "$METVIEW_MSG_FILE" = "" ]
	then
		METVIEW_MSG_FILE=$METVIEW_TMPDIR/infos
		rm -f $METVIEW_MSG_FILE > /dev/null 2>&1
	fi
	echo "$@"      >> $METVIEW_MSG_FILE
	echo "$me: $@" 1>&2
}

# -------------------------------------------------------------

cleanup(){
	status=$?
	trap "" EXIT ERR

	if [ $METVIEW_MODE != python ]
	then
		if [ "$status" = "0" ]
		then
			echo "`basename $0`: $1 (OK) (line $2), exit status $status, starting 'cleanup'"
		else
			echo "`basename $0`: $1 on ERROR (line $2), exit status $status, starting 'cleanup'"
		fi
	fi

	# Look for old metview cache directories
	if [ $METVIEW_MODE = interactive -a x$MV_SILENT = xNO -a "x$MV_HELP_FLAG" != x2 ]
	then

		if [ $METVIEW_GUI_BUILT = true ]
		then
			# restore stdout/stderr, but these will not have been set
			# up if we have a batch only mode
			exec 1>&5
			exec 2>&6
		fi

		# Get names of possible old metview tmpdirs for warnings
		# Note: $oldtmp will include also the current cache dir :-(
		if [ X`echo $METVIEW_TMPDIR | grep "jtmp\."` != X ]
		then
			#-- ECMWF workstation: cache under a dynamic parent dir --
			oldtmp=`ls -d $METVIEW_TMPDIR/../../jtmp.*/mv.*.$LOGNAME 2> /dev/null` || true
		else
			#-- cache should be under a static parent dir --
			oldtmp=`ls -d $METVIEW_TMPDIR/../mv.*.$LOGNAME 2> /dev/null` || true
		fi

		# print the list of old directories
		# if only one dir then that must be the current one => no printing!
		current_tmp_bname=`basename "$METVIEW_TMPDIR"`
		if [ `echo $oldtmp | wc -w` -gt 1 ]
		then
		info "Found several metview cache directories:"
		info " "
		for n in $oldtmp
		do
			nb="`basename $n`"
			if [ $nb != $current_tmp_bname ]
			then
				info "`cd $n ; ls -ld $PWD`"
			fi
		done
			info " "
			info "Old ones can be removed with 'rm -rf <dir>'"
#            for n in $oldtmp
#            do
#                nb="`basename $n`"
#                if [ $nb != $current_tmp_bname ]
#                then
#                    info "rm -rf `cd $n ; ls -ld $PWD`"
#                fi
#            done
#            info " "
#            info "DO NOT remove the current cache dir: $METVIEW_TMPDIR"
			info " "
		fi
	fi


	rm -fr $METVIEW_TMPDIR || true
	rm -f $METVIEW_USER_DIRECTORY/System/.$MV_TMPDIR_LINK || true
	rm -Rf $METVIEW_USER_DIRECTORY/System/$MV_TMPDIR_LINK || true
	if [ -d $METVIEW_TMPDIR ]
	then
	   echo " >> Metview cache $METVIEW_TMPDIR still exists, retry in 10 secs..."
	   sleep 10
	   rm -fr $METVIEW_TMPDIR || true
	fi
	if [ -d $METVIEW_TMPDIR ]
	then
	   echo " >> Metview cache $METVIEW_TMPDIR still exists, retry in 30 secs..."
	   sleep 30
	   rm -fr $METVIEW_TMPDIR || true
	fi

	exit $status
}


# -------------------------------------------------------------
# Users have links in their 'metview' user directory to certain
# system directories. These links are mainly created when the
# user starts Metview for the first time and are hard-coded to
# the directory where that version of Metivew was installed. This could
# become a problem if that directory is removed when a new version
# is installed. This function updates those links to the appropriate
# directory of THIS version of Metview.

ensure_system_dir_links_correct(){

    # we just want one link to maintain:
    # ~/metview/System/.System  ($METVIEW_USER_SYSTEM_LINK)
    # - and all other system directories will be children of that.

    METVIEW_USER_SYSTEM_LINK=$METVIEW_USER_DIRECTORY/System/.System


	if [ ! -h $METVIEW_USER_SYSTEM_LINK ] # link does not exist?
    then
        echo "creating new system link: $METVIEW_USER_SYSTEM_LINK -> $METVIEW_LINK_DIR"
        ln -s "$METVIEW_LINK_DIR" "$METVIEW_USER_SYSTEM_LINK" # then create it


        # for each of the following sub-directories, remove the current link and create a new
        # one which points to the newly-created System link.
        # The following lines set KSH arrays.

        local_dirs=("System Drawers" "System Templates")
        sys_dirs=(   Drawers          Templates)

        for i in 0 1
        do
            if [ x$MV_QUIET != "x-quiet" ]
            then
                info "Updating link: $METVIEW_USER_DIRECTORY/System/${local_dirs[i]} -> .System/${sys_dirs[i]}"
            fi

            rm -f "$METVIEW_USER_DIRECTORY/System/${local_dirs[i]}"
            ln -s ".System/${sys_dirs[i]}" "$METVIEW_USER_DIRECTORY/System/${local_dirs[i]}"
        done

    else
        # in this case, the System link does already exist - we'll just make
        # sure it's up-to-date.

        #if [ x$MV_SILENT = xNO ]
        #then
            # this message can be annoying. Ideally, we'd like to only print it if we are changing
            # the link, but we have no way of knowing what the existing link is already pointing to
            # (unless we parse the result of 'ls -l' on it).
            # info "updating system link: $METVIEW_USER_SYSTEM_LINK -> $METVIEW_LINK_DIR"
        #fi

        rm -f  "$METVIEW_USER_SYSTEM_LINK"
        ln -s "$METVIEW_LINK_DIR" "$METVIEW_USER_SYSTEM_LINK"
    fi
}


# -------------------------------------------------------------

checkoption() {

while [ "$1" != "" ]
do
	case "$1" in
		-F)
			METVIEW_FONTS=DemoFonts
			;;

		-log)
			METVIEW_LOG=$2
			if [ "$METVIEW_LOG" = "-" ]
			then
			  MV_SLOG=yes
			  shift
			elif [ "X$METVIEW_LOG" = "X" -o "`echo $METVIEW_LOG | cut -c1`" = "-" ]
			then
			  METVIEW_LOG=default_log
			else
			  shift
			fi
			MV_QUIET=" "
			MV_SLOG=no
			MV_DEBUG_PRINT=1
			;;


		-qlog)
			MV_QLOG=yes
			MV_SLOG=yes
			MV_QUIET=" "
			METVIEW_CMD=""
			;;

		-slog)
			MV_SLOG=yes
			MV_QUIET=" "
			METVIEW_CMD=""
			;;

		-mlog)
			MV_MLOG=yes
			MV_QLOG=yes
			MV_SLOG=yes
			MV_QUIET=" "
			METVIEW_CMD=""
			;;

#		-m)
#			MAGPLUS_HOME=$2
#			MAGPLUS_LIBDIR=`${MAGPLUS_HOME}/bin/magics-config --libdir`
#			LD_LIBRARY_PATH="${MAGPLUS_LIBDIR}:${LD_LIBRARY_PATH}"
#			shift
#			;;

		-display)
			DISPLAY=$2
			shift
			;;

		-nocreatehome)
			NOCREATE_MVHOME=YES
			;;

		-u)
			METVIEW_USER_DIRECTORY=$2
			shift
			;;

		-v)
			echo " $METVIEW_VERSION_TITLE @ `hostname`"
			;;

		-q)
			MV_SILENT=YES
			;;

		-b)
			macro=$2
			shift 2
			METVIEW_MODE=batch
			if [ ! -f "$macro" ]
			then
				info "Cannot find file $macro"
				exit 1
			fi
			args=$METVIEW_TMPDIR/macro.args.$$
			touch $args
			while [ "$1" != "" ]
			do
				echo "$1" >> $args
				shift
			done
			METVIEW_STARTUP="$METVIEW_BIN/macro -script '$macro' -args $args"
			[ $METVIEW_LOG = no_log -o "$METVIEW_LOG" = "-" ] && METVIEW_CMD=""
			break
			;;

		-p)
			METVIEW_MODE=uplotSA   # plot standalone
			inputdir=$(cd "$(dirname "$2")" ; pwd -P )  # make sure the filename contains the full path
			basefile=$(basename "$2")
            inputfile=$inputdir/$basefile
			if [ ! -f "$inputfile" ]
			then
				info "Cannot find file $inputfile ($2)"
				exit 1
			fi
			METVIEW_STARTUP="$METVIEW_BIN/uPlot '$inputfile'"
			METVIEW_EXIT=uPlot
			shift 1
			;;

		-e)
			METVIEW_MODE=examine


            if [ $# -lt 2 ] ; then
                info 'Invalid arguments'
                info 'Usage: metview -e [grib|bufr|geopoints|netcdf|odb] file_path'
                exit 1
            fi

            first_arg=$2
            shift
            if [ $# -ge 2 ] ; then
                second_arg=$2
                if [[ $(echo $second_arg | cut -c 1) == "-" ]] ; then
                    METVIEW_STARTUP="$METVIEW_BIN/MvExamineManager '$first_arg'"
                else
                    METVIEW_STARTUP="$METVIEW_BIN/MvExamineManager '$first_arg' '$second_arg'"
                    shift
                fi
            else
                METVIEW_STARTUP="$METVIEW_BIN/MvExamineManager '$first_arg'"
            fi

#            info 'METVIEW_STARTUP='$METVIEW_STARTUP
#            info 'ARGS=' $# $*
			METVIEW_EXIT=MvExamineManager
			;;

		-python-serve)
			METVIEW_STARTUP="$METVIEW_BIN/PythonServe -serve -nofork"
			METVIEW_MODE=python
			METVIEW_EXIT=PythonServe
			METVIEW_CMD=""
			# $2 = temporary file name, $3 = pid of Python process to communicate back to
			MV_PY_TEMP_FILE=$2
			MV_PY_PID=$3
			shift 2
			;;

		-s)
			METVIEW_STARTUP=$2
			METVIEW_MODE=batch
			shift
			;;

		-H)
			MV_HELP_FLAG=1
			;;

		-h)
			MV_HELP_FLAG=2
			;;

		-mfdbg)
			MACRO_FORTRAN_DBG=$2
			MACRO_EXTRA_F77_FLAGS=${MACRO_EXTRA_F77_FLAGS:=-g}
			MACRO_EXTRA_F90_FLAGS=${MACRO_EXTRA_F90_FLAGS:=-g}
			MACRO_EXTRA_CC_FLAGS=${MACRO_EXTRA_CC_FLAGS:=-g}
			shift
			;;

		-edbg)
			MV_DBG=$2
			shift
			;;

		-wr)
			MV_WEATHER_ROOM="1"
			if [ "$MV_WEATHER_ROOM_BUILT" != "true" ]
			then
				info "-wr option not valid: Weather Room export facility not available in this build"
				exit 1
			fi
			;;

		-eccharts)
			METVIEW_ECCHARTS=1
			;;

                -dark)
                        MV_USER_UI_THEME="dark"
                        ;;

                -light)
                        MV_USER_UI_THEME="light"
                        ;;

        -xserv)
            MV_DEV_APPLICATION=xserv
            ;;

        -fs)
            export MV_FONT_SIZE=$2
            shift
            ;;

		*)
			echo "$me: option not supported \"$1\"" 1>&2
			exit 1
			;;

	esac
    shift
done
}

# =============================================================
#                    end  f u n c t i o n s
# =============================================================

# for script debugging, set MV_SCRIPT_DEBUG externally
[ x$MV_SCRIPT_DEBUG != x ] && set -x


# set the version (prod or dev). When running on a local development
# version, we just set 'dev' here. When installed, this is overwritten
# in the installed version and set to 'prod'.
METVIEW_VERSION=prod



case $METVIEW_VERSION in

 dev)
	METVIEW_DIR=${METVIEW_DIR_DEV}
	METVIEW_DIR_SHARE=${METVIEW_DIR_DEV}
	METVIEW_BIN=${METVIEW_BIN:=$METVIEW_DIR/bin}
	METV_DEV=yes
	MV_DEBUG_PRINT=${MV_DEBUG_PRINT:=1}
    # if building as part of a bundle, and running from the build directory,
    # then make sure we pick up the resource files from the other packages
    # in the build directory
    if [ "$MV_BUNDLE_CONTAINS_METVIEW" != "x" ]
    then
        MV_BUILD_ROOT=${METVIEW_DIR}/metview
		if [ "$MV_BUNDLE_CONTAINS_MAGICS" != "x" ]
		then
			MAGPLUS_HOME=
		fi
        if [ "$MV_BUNDLE_CONTAINS_EMOSLIB" != "x" ]
		then
			BUFR_TABLES=${MV_BUNDLE_SRC}/bufrdc_tables
        	MARS_LSM_PATH=${MV_BUNDLE_SRC}/libemos/tables/interpol
		fi
		if [ "$MV_BUNDLE_CONTAINS_ECCODES" != "x" ]
		then
        	METVIEW_EXTRA_GRIB_DEFINITION_PATH="${METVIEW_DIR_DEV}/share/eccodes/definitions:${METVIEW_EXTRA_GRIB_DEFINITION_PATH}"
        	METVIEW_EXTRA_GRIB_SAMPLES_PATH="${METVIEW_DIR_DEV}/share/eccodes/samples"
        	GRIBAPI_DIR=${METVIEW_DIR_DEV}		
		fi

        #FDB_CONFIG_FILE=/tmp/cgi/git/metview-bundle/fdb/etc/Config  # has no effect
        #FDB_CONF_FILE=/tmp/cgi/git/metview-bundle/fdb/etc/Config    # has no effect
    else
        MV_BUILD_ROOT=${METVIEW_DIR}
    fi

    METVIEW_LIB=$METVIEW_DIR/lib
    LD_LIBRARY_PATH="${METVIEW_LIB}:${LD_LIBRARY_PATH}:${MV_BUILD_ROOT}/src/Macro:${MV_BUILD_ROOT}/src/libMetview:${MV_BUILD_ROOT}/src/libUtil:${MV_BUILD_ROOT}/src/libFTimeUtil"
    # echo "LD: ${LD_LIBRARY_PATH}"


	;;

 prod)
	METVIEW_DIR=$INSTALLDIR
	METVIEW_DIR_SHARE=${METVIEW_DIR}
	METVIEW_BIN=${METVIEW_BIN:=$METVIEW_DIR/bin/metview_bin}
	METVIEW_LIB=$METVIEW_DIR/lib/aarch64-linux-gnu
	LD_LIBRARY_PATH=$METVIEW_LIB:$LD_LIBRARY_PATH
	METV_DEV=no

	if [[ "${uname_}" == 'Darwin' ]]; then
		DYLD_LIBRARY_PATH=$METVIEW_LIB:$DYLD_LIBRARY_PATH
	fi



	if [ "$MV_BUNDLE_CONTAINS_MAGICS" != "x" ]
	then
		MAGPLUS_HOME=$INSTALLDIR
	fi
	;;
esac


# =============================================================

me=`basename $0`

# =============================================================
# Create Metview cache directory as a subdir of:
# - if user has set METVIEW_TMPDIR then use it
# - else if script /usr/local/share/metview_env exists then
#     use it to define cache dynamically (depending on the host)
# - else if TMPDIR has been set then use it
# - else use /tmp

TMPDIR=${TMPDIR:=/tmp}
[ -f /usr/local/share/metview_env ] && . /usr/local/share/metview_env
TMPDIR=${METVIEW_CACHE_ROOT:=$TMPDIR}
METVIEW_TMPDIR=${METVIEW_TMPDIR:=$TMPDIR}

# check that METVIEW_TMPDIR actually exists - we can't run without it

if [ ! -d $METVIEW_TMPDIR ]
then
    echo ""
    echo "  Temporary directory '$METVIEW_TMPDIR' does not exist"
    echo "  Metview needs this in order to run. Check that environment"
    echo "  variable \$TMPDIR is set to a valid directory and try again."
    exit 1
fi

# warning: src/MetviewUI/Path.cc: hardcoded length 17+"$$"
MV_TMPDIR_LINK=MvTemporaryCache_$$



METVIEW_TMPDIR=$METVIEW_TMPDIR/mv.$$.$LOGNAME
mkdir -p $METVIEW_TMPDIR
# assign also to TMPDIR for historical reasons
TMPDIR=$METVIEW_TMPDIR


# =============================================================
# cache directory cleaned automatically at end or at error.
# on new platforms check that these signals are valid:

MV_SIGLIST="HUP INT QUIT TERM XCPU  XFSZ"
#           1   2   3    15   30/24 31/25

# PWR (19/29 was removed 2014-04 for MacOS X)

trap 'cleanup "EXIT" $LINENO' EXIT
# removed because failing logical tests triggered an ERR on AIX
#trap 'cleanup "ERR trap" $LINENO' ERR
trap 'cleanup "SIGNAL trap" $LINENO' $MV_SIGLIST

# =============================================================
METVIEW_USER_DIRECTORY=${METVIEW_USER_DIRECTORY:=$HOME/metview}
METVIEW_LINK_DIR=${METVIEW_LINK_DIR:=$METVIEW_DIR_SHARE/app-defaults}

# =============================================================
# Config files and 'can_be_created' variables

TRUE_IF_ECMWF=true
[ $WMO_SITE_NR != 098 ] && TRUE_IF_ECMWF=false

TRUE_IF_MARS_AVAILABLE=true
[ "$MV_MARS_ACCESS" = "MARS_none" ] && TRUE_IF_MARS_AVAILABLE=false

# -- redefined for ECMWF later ! --
MARS_LANGUAGE_FILE=${MARS_LANGUAGE_FILE:=$METVIEW_DIR_SHARE/etc/MarsDef}
MARS_TEST_FILE=${MARS_TEST_FILE:=$METVIEW_DIR_SHARE/etc/MarsRules}


# activate warnings/failure for 2 digit years
#MARS_Y2K=${MARS_Y2K:=1}
#MARS_Y2K_FAIL=${MARS_Y2K_FAIL:=1}

# activate Emoslib automatic resolution sh->gp
MARS_AUTO_RESOL=${MARS_AUTO_RESOL:=1}

# nr of forked copies of a Metview process
# parameter 'maxforks' for individual services in configs
MARS_MAXFORKS=${MARS_MAXFORKS:=6}

# =============================================================
# Misc.

#METVIEW_BUG_MAIL=${METVIEW_BUG_MAIL:=metviewdev}

METVIEW_STARTUP=Desktop
METVIEW_EXIT=Desktop
METVIEW_FONTS=NormalFonts

#-- by default, use the system grib_dump --
METVIEW_GRIB_DUMP=${METVIEW_GRIB_DUMP:=${GRIBAPI_DIR}/bin/grib_dump}

#-- by default, use the system bufr command line tools --
METVIEW_BUFR_DUMP=${METVIEW_BUFR_DUMP:=${GRIBAPI_DIR}/bin/bufr_dump}
METVIEW_BUFR_FILTER=${METVIEW_BUFR_FILTER:=${GRIBAPI_DIR}/bin/bufr_filter}
METVIEW_BUFR_COPY=${METVIEW_BUFR_COPY:=${GRIBAPI_DIR}/bin/bufr_copy}

# =============================================================
case $METVIEW_VERSION in

 dev)
   METVIEW_CMD=${METVIEW_CMD:="xterm -iconic -e"}
   #timeout=${METVIEW_TIMEOUT:=60}
   timeout=${METVIEW_TIMEOUT:=240}
   # METVIEW_CONFIG_FILES=$METVIEW_CONFIG_FILES:ObjectList.forTesting
   ;;

 prod)
   timeout=${METVIEW_TIMEOUT:=5}
   ;;
esac

# =============================================================
# execute site dependent stuff from another file (if exists),
# do not crash on errors!

if [ -f $METVIEW_BIN/metview_local.$MV_ENVIRON ]
then
  . $METVIEW_BIN/metview_local.$MV_ENVIRON || true
fi


# create a temporary directory in case we need to decode PrepBUFR files
mkdir -p $METVIEW_TMPDIR/bufr_def


# =============================================================
# Set up the grib/bufr definition path to use local tables used within metview

export GRIB_DEFINITION_PATH="${METVIEW_DIR_SHARE}/etc/grib_def/definitions:/usr/./share/eccodes/definitions:$METVIEW_TMPDIR/bufr_def"
export GRIB_SAMPLES_PATH="${METVIEW_DIR_SHARE}/etc/grib_def/samples:/usr/./share/eccodes/samples"

# =============================================================
# Set up extra grib definition paths. It has to be done after metview.local
# is called because it might call set_mars_env which unset all GRIB API related
# env variables!

METVIEW_EXTRA_GRIB_DEFINITION_PATH=${METVIEW_EXTRA_GRIB_DEFINITION_PATH:=""}
if [ "x$METVIEW_EXTRA_GRIB_DEFINITION_PATH" != x -a "x$GRIBAPI_DIR" != x ] ; then
  GRIB_DEFINITION_PATH="${METVIEW_EXTRA_GRIB_DEFINITION_PATH}:${GRIB_DEFINITION_PATH}"
fi

METVIEW_EXTRA_GRIB_SAMPLES_PATH=${METVIEW_EXTRA_GRIB_SAMPLES_PATH:=""}
if [ "x$METVIEW_EXTRA_GRIB_SAMPLES_PATH" != x -a "x$GRIBAPI_DIR" != x ] ; then
  export GRIB_SAMPLES_PATH="${METVIEW_EXTRA_GRIB_SAMPLES_PATH}:${GRIB_SAMPLES_PATH}"
fi


# also for ECCODES_DEBUG
ECCODES_DEBUG=$MV_ECCODES_DEBUG
unset MV_ECCODES_DEBUG



# ==============================================================
# This is a safety measure to guarantee that the default definition path
# of the eccodes version metview was built with is used. If users want to use
# their own grib definitions they need to set METVIEW_EXTRA_GRIB_DEFINITION_PATH.
# Please note that mars (at ECMWF) unsets this env variable during setup!!!

unset ECCODES_DEFINITION_PATH

# =============================================================
# extra stuff (e.g. local DataAccess objects)
#
#if [ -f $METVIEW_BIN/extra.$MV_ENVIRON ]
#then
#  . $METVIEW_BIN/extra.$MV_ENVIRON || true
#fi

# =============================================================
# Check that some variables have been set

#[ "X$MAGPLUS_HOME" != "X" ] &&  checkvar MAGPLUS_HOME dir
# checkvar other ?...

# =============================================================
# Set up more variables

METVIEW_STATIONS=${METVIEW_STATIONS:=$METVIEW_DIR_SHARE/etc/stations}

METVIEW_NEWS=${METVIEW_NEWS:=$METVIEW_LINK_DIR/news}

MARS_ACCOUNT_FILE=${MARS_ACCOUNT_FILE:=/usr/local/lib/metaps/etc/account}
MARS_COMPUTE_FLAG=${MARS_COMPUTE_FLAG:=254}

METVIEW_MODE=interactive
METVIEW_LOG=no_log
MV_QLOG=${MV_QLOG=no}
MV_SLOG=${MV_SLOG=no}
MV_MLOG=${MV_MLOG=no}
MV_QUIET=${MV_QUIET:=-quiet}
MV_SILENT=${MV_SILENT:=NO}

#Set the desktop app name
MV_DESKTOP_NAME=Desktop

#===============================================================
# Setup Qt graphics system flag for Qt applications

METVIEW_GRAPHICS_SYSTEM=${METVIEW_GRAPHICS_SYSTEM:="raster"}

if [ "$METVIEW_GRAPHICS_SYSTEM" != "raster" -a "$METVIEW_GRAPHICS_SYSTEM" != "native" ]
then
	echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1"
	echo "WARNING: METVIEW_GRAPHICS_SYSTEM is set to an invalid value: $METVIEW_GRAPHICS_SYSTEM"
	echo "The possible values are: 'raster' and 'native'. Metview will be started up"
	echo "with value 'raster'."
	echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
	METVIEW_GRAPHICS_SYSTEM="raster"
fi

METVIEW_QT_APPLICATION_FLAGS="-graphicssystem $METVIEW_GRAPHICS_SYSTEM"
METVIEW_QT_STYLE="Fusion"

# =============================================================
# Add metview bin to path
PATH=$METVIEW_BIN::$PATH

# =============================================================
# Process options. Don't use getopt because of stupid hp

[ $# -gt 0 ] && checkoption "$@"


# print out some details if -slog
if [ "X$MV_SLOG" = "Xyes" ]
then
    echo "$METVIEW_VERSION_TITLE @ `hostname`"
    echo "Installed in $METVIEW_DIR"
fi


# =============================================================
# Change the application to start up in dev mode based on
# command line arguments

if [ "$METVIEW_VERSION" = "dev"  -a "${MV_DEV_APPLICATION}" = "xserv" ] ; then
    METVIEW_STARTUP=xserv
    METVIEW_EXIT=xserv
fi

# =============================================================
# Quick abort if Metview has been built in batch-only mode
# but the user has requested an interactive session

if [ $METVIEW_MODE = interactive -a $METVIEW_GUI_BUILT != true ]
then
    echo ""
    echo "This Metview has been built without user interface."
    echo "Please run with the -b option."
    echo ""
    exit 1
fi


# =============================================================
# Check: the -nocreatehome option is only for batch mode

if [ $METVIEW_MODE = interactive -a "x$NOCREATE_MVHOME" = "xYES" ]
then
    echo ""
    echo "Option -nocreatehome is only valid when running in batch mode"
    echo "Please run with the -b option."
    echo ""
    exit 1
fi


# =================
# Make sure METVIEW_USER_DIRECTORY is a full path name

case $METVIEW_USER_DIRECTORY in

	/*)
		;;
	*)
		METVIEW_USER_DIRECTORY=`pwd`/$METVIEW_USER_DIRECTORY
		;;
esac

# =============================================================
# Create Metview user directory if missing and NOCREATE_MVHOME is not set

uname_=`uname`
if [[ "${uname_}" == 'Darwin' ]]; then
      # on the MAC, 'dot' files in .tar.gz are treated specially - we want
      # to disable this special behaviour so that we don't get spurious
      # files appearing. See discussion here:
      #   http://superuser.com/questions/61185/why-do-i-get-files-like-foo-in-my-tarball-on-os-x
      COPYFILE_DISABLE=1
fi



# if NOCREATE_MVHOME was set, then if the METVIEW_USER_DIRECTORY
# does not exist, do not create it; also, in this case, set
# METVIEW_USER_DIRECTORY to something that is unlikely to be able
# to be created by a normal user

if [ ! -d "$METVIEW_USER_DIRECTORY/System" ]
then
    if [ "x$NOCREATE_MVHOME" != "xYES" ]
    then
	    # note that since changing the scripts to bash, we need to be aware that the
	    # modules system can overwrite the variable METVIEWDIR in a new shell
	    . metview_create_user_dir "$METVIEW_USER_DIRECTORY"
    else
        METVIEW_USER_DIRECTORY="/NOHOME"
    fi
fi


if [ $METVIEW_MODE = interactive ]
then
	# check whether the 'Metview' directory exists - if it doesn't, then we
	# won't be able to create the system dir link. It's not completely vital
	# to have this directory, so we won't abort, but we will issue a warning.

	if [ -d "$METVIEW_USER_DIRECTORY/System" ]
	then
		# if used interactively, make sure that the links to system dirs are
		# correct for this version.
		ensure_system_dir_links_correct
	else
		echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
		echo "WARNING: Directory $METVIEW_USER_DIRECTORY/System does not exist!"
		echo "Please contact your Metview administrator or your system administrator to re-install it."
		echo "Metview will run, but some functionality may not be available."
		echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
	fi


    # External macro editor setup

    EDITOR=${EDITOR:=vi}
    METVIEW_EDITOR=${METVIEW_MACRO_EDITOR:=$EDITOR}

    case `basename $METVIEW_EDITOR` in

	    vi|vim|ed)
	    # curses editors, xterm needed
	    METVIEW_EDITOR="xterm -e $METVIEW_EDITOR"
	    ;;

	    neditmv)
	    # specialised NEdit editor. Check whether a complete path was given.
	    # We want to replace 'neditmv' with 'nedit -lm Metview_Macro'.
	    ed_dir=`dirname $METVIEW_EDITOR`
	    if [ "$ed_dir" = "." ]
	    then
		    METVIEW_EDITOR='nedit -lm Metview_Macro'
	    else
		    METVIEW_EDITOR=`dirname $METVIEW_EDITOR`/'nedit -lm Metview_Macro'
	    fi
	    ;;

		dtpad|emacs|ie|jot|nedit|xedit|xemacs|gvim|kate|kwrite|gedit|mate|subl|atom)
	    # X Based editor
	    ;;

	    *)
	    info "unknown editor $METVIEW_EDITOR (will be started with xterm)"
	    METVIEW_EDITOR="xterm -e $METVIEW_EDITOR"
	    ;;
    esac


 
    # set up the file viewers
    if [[ "${uname_}" == 'Darwin' ]]; then
      MV_BROWSER_NAME=${MV_BROWSER_NAME:=open}
      METVIEW_PS_VIEWER=${METVIEW_PS_VIEWER:=open}
      METVIEW_PDF_VIEWER=${METVIEW_PDF_VIEWER:=open}
      METVIEW_PNG_VIEWER=${METVIEW_PNG_VIEWER:=open}
      METVIEW_JPEG_VIEWER=${METVIEW_JPEG_VIEWER:=open}
      METVIEW_GIF_VIEWER=${METVIEW_GIF_VIEWER:=open}
      METVIEW_TIFF_VIEWER=${METVIEW_TIFF_VIEWER:=open}
      METVIEW_RASTER_EDITOR=${METVIEW_RASTER_EDITOR:=open}
      METVIEW_TEXT_VIEWER=${METVIEW_TEXT_VIEWER:=open}
      METVIEW_GRAPHICS_SYSTEM=${METVIEW_GRAPHICS_SYSTEM:="native"}
      MV_VAPOR_BIN=${MV_VAPOR_BIN:="/Applications/VAPOR/VAPOR.app/Contents/MacOS/"}
#      MARS_NOFORK=1

      # Qt5 settings on mac
      # This should be safe enough on Qt6 too, but not necessary
      QT_MAC_WANTS_LAYER=1

    else
      METVIEW_PS_VIEWER=${METVIEW_PS_VIEWER:=gv}
      METVIEW_PDF_VIEWER=${METVIEW_PDF_VIEWER:=display}
      METVIEW_PNG_VIEWER=${METVIEW_PNG_VIEWER:=display}
      METVIEW_JPEG_VIEWER=${METVIEW_JPEG_VIEWER:=display}
      METVIEW_GIF_VIEWER=${METVIEW_GIF_VIEWER:=display}
      METVIEW_TIFF_VIEWER=${METVIEW_TIFF_VIEWER:=display}
	  METVIEW_TEXT_VIEWER=${METVIEW_TEXT_VIEWER:=$METVIEW_EDITOR}
      METVIEW_RASTER_EDITOR=${METVIEW_RASTER_EDITOR:=gimp}
      METVIEW_KML_VIEWER=${METVIEW_KML_VIEWER:=google-earth}


      resY=""
      if [[ $(which xdpyinfo 2>/dev/null) ]]; then
        resY=$(xdpyinfo | grep "resolution" | awk '{print $2}' | cut -d "x" -f 2) || true
      fi
      METVIEW_SCREEN_RESOLUTION=${METVIEW_SCREEN_RESOLUTION:=$resY}

    fi
    #########
    # URLs
    METVIEW_URL=${METVIEW_URL:=http://www.ecmwf.int/publications/manuals/metview}
    WEBMARS_URL=${WEBMARS_URL:=http://www.ecmwf.int/services/archive}

    #########
    # News tool

    #-- 1st: if $MVNEWSMAIL has been set,
    #---- 2nd: if $HOME/Mail/MvNewsMail exists,
    #------ 3rd: if $HOME/MozMail/MvNewsMail exists,
    #-------- 4th: if $HOME/nsmail/MvNewsMail exists,
    #---------- 5th: if $MAIL has been set,
    #------------ 6th: /var/spool/mail/$LOGNAME
    if [ x$MVNEWSMAIL != x ]
    then
       MAIL=$MVNEWSMAIL
    elif [ -f $HOME/Mail/MvNewsMail ]
    then
       MVNEWSMAIL=$HOME/Mail/MvNewsMail
       MAIL=$MVNEWSMAIL
    elif [ -f $HOME/MozMail/MvNewsMail ]
    then
       MVNEWSMAIL=$HOME/MozMail/MvNewsMail
       MAIL=$MVNEWSMAIL
    elif [ -f $HOME/nsmail/MvNewsMail ]
    then
       MVNEWSMAIL=$HOME/nsmail/MvNewsMail
       MAIL=$MVNEWSMAIL
    else
       MAIL=${MAIL:=/var/spool/mail/$LOGNAME}
    fi

fi


# ===============================================================
# Path to external macros

user_extern_path=""
[ x$METVIEW_MACRO_PATH != x ] && user_extern_path="$METVIEW_MACRO_PATH:"
user_metview_path="$METVIEW_USER_DIRECTORY/System/Macros/$OS:$METVIEW_USER_DIRECTORY/System/Macros"
system_path="$METVIEW_LINK_DIR/CommonMacroFuncs/$OS:$METVIEW_LINK_DIR/CommonMacroFuncs"
METVIEW_MACRO_PATH="${user_extern_path}${user_metview_path}:${system_path}"

# ===============================================================
# Config

XENVIRONMENT=$METVIEW_TMPDIR/Metview
MARS_CONFIG=$METVIEW_TMPDIR/config

# ===============================================================
# Build resource file

sed -e 's:\$METVIEW_DIR_SHARE:'"$METVIEW_DIR_SHARE:" \
		$METVIEW_DIR_SHARE/app-defaults/Metview    >  $METVIEW_TMPDIR/Metview
cat $METVIEW_DIR_SHARE/app-defaults/$METVIEW_FONTS >> $METVIEW_TMPDIR/Metview

# ===============================================================
# Config file

#-- do not use full address 'name-at-ecmwf-dot-int'
#UserSupportMailAddress=${METVIEW_SUPPORT_MAIL:=metview}
metview_command=${METVIEW_CMD:=''}



# XXXXXXXXXXX to deal with!
rm -f $METVIEW_TMPDIR/config
[ -f $HOME/.metviewrc ] && cp $HOME/.metviewrc  $METVIEW_TMPDIR/config



. $METVIEW_DIR_SHARE/etc/ObjectListAll >> $METVIEW_TMPDIR/config



# ===============================================================
# Run script patches from another file

# . $METVIEW_BIN/metview_patches || true


# =============================================================
# execute site dependent post-stuff from another file
# (if exists), do not crash on errors!

if [ -f $METVIEW_BIN/metview_local2.$MV_ENVIRON ]
then
  . $METVIEW_BIN/metview_local2.$MV_ENVIRON || true
fi



# option to change the default MARS interpolation package
METVIEW_MARS_INTERP=${METVIEW_MARS_INTERP:=MIR}
if [ "$METVIEW_MARS_INTERP" == "MIR" ]
then
    if [ "x$MV_MIR" == "x1" ]
    then
        #export MV_MARS_MODE=MIR
        export MARS_PPROC_BACKEND=MIR
        #echo "Using MIR as interpolation package for MARS requests and DivRot functions"
    else
        echo "METVIEW_MARS_INTERP is set to MIR, but this Metview version was not built with MIR support. Will use emoslib."
    fi
else
    if [ "$METVIEW_MARS_INTERP" != "EMOS" ]
    then
        echo "METVIEW_MARS_INTERP can only be MIR or EMOS, but it is $METVIEW_MARS_INTERP - aborting"
        exit 1
    fi
    export MARS_PPROC_BACKEND=EMOS
fi


# print help info?
if [ "x$MV_HELP_FLAG" != x ]
then
  $METVIEW_BIN/metview_help
  if [ "x$MV_HELP_FLAG" = x2 ]
  then
    exit 0
  fi
fi



# =============================================================
. $METVIEW_BIN/metview_stat
# =============================================================



# =============================================================
if [ $METVIEW_MODE = python ]
then
	MV_EVENT_PARAMS="-environment $MV_PY_TEMP_FILE -exit PythonServe"
	#. $METVIEW_BIN/python_feedback $MV_PY_TEMP_FILE $MV_PY_PID
else
	MV_EVENT_PARAMS=""
fi
# =============================================================


# no core files
ulimit -c 0

if [ $METVIEW_MODE = batch -o $METVIEW_MODE = python ]
then
#	echo "Batch" > $METVIEW_TMPDIR/123_MV_MODE
#	chmod 777 $METVIEW_TMPDIR/123_MV_MODE
	# get '$MACRO_STARTUP' to Event without expansion!
	MACRO_STARTUP="$metview_command $METVIEW_STARTUP"
	$metview_command $METVIEW_BIN/event $MV_EVENT_PARAMS $MV_QUIET -startup "\$MACRO_STARTUP"

else
#	echo "Interactive" > $METVIEW_TMPDIR/123_MV_MODE
#	chmod 777 $METVIEW_TMPDIR/123_MV_MODE

	### not so relevant with QT??? $METVIEW_BIN/checkdisplay

	# Set text for MetviewUI titlebar
	METVIEW_VERSION_TITLE="$METVIEW_VERSION_TITLE @ `hostname`" || true

	# prevent core files eating users disk quota
	if [ $METV_DEV = no -a $METVIEW_MODE != examine ]
	then
#	  SCRATCH=${SCRATCH:=$METVIEW_TMPDIR/..}
#	  cd $SCRATCH
	  cd $METVIEW_TMPDIR/..
	fi

	# Close tty
    exec  < /dev/null

    exec 5>&1   # store for later
    exec 6>&2   # store for later

    if [ X$METVIEW_LOG = Xno_log -a X$MV_SLOG = Xno -a x$MV_DBG = x ]
    then
      exec 1> /dev/null
      exec 2> /dev/null
    fi

	if [ "x$MV_DBG" != x ]
	then
		echo " Event startup parameters:"
		echo "     -startup '$METVIEW_STARTUP' -exit $METVIEW_EXIT"
		$MV_DBG $METVIEW_BIN/event $MV_EVENT_PARAMS
	else
		$metview_command $METVIEW_BIN/event $MV_EVENT_PARAMS -startup '$METVIEW_STARTUP ${METVIEW_QT_APPLICATION_FLAGS}' \
			 -exit $METVIEW_EXIT
	fi
fi
