
# **************************** LICENSE START ***********************************
#
# Copyright 2014 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 ************************************

#----------------- start of file ./scripts/metview_base
#
# Metview scripts are build automatically by 'make'.
#
# NOTE: two external files for customising, they are executed
#       only if they exist ($MV_ENVIRON from config/CONFIG.site):
#   - 'metview_local.$MV_ENVIRON' (for pre-stuff i.e. to set site dep values)
#   - 'metview_patches'
#   - '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 [ "$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

	# 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.

        set -A local_dirs "System Drawers" "System Templates"
        set -A 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
			;;

		-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
			;;

		-e)
			METVIEW_MODE=examine
			datatype=$2
			inputfile=$3
	
			if [ "$datatype" = "odb" -o "$datatype" = "ODB"  ]
			then
				if [  -a ! -f "$inputfile" -a ! -d "$inputfile" ]
				then
					info "Cannot find file/directory $inputfile"
					exit 1
				fi
			elif [ ! -f "$inputfile" ]
			then
				info "Cannot find file $inputfile"
				exit 1
			fi

			METVIEW_STARTUP="$METVIEW_BIN/MvExamineManager $datatype '$inputfile'"
			METVIEW_EXIT=MvExamineManager
			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
			;;

		-desktop)			
			MV_DESKTOP_NAME="Desktop"
			if [ "$METVIEW_VERSION" = "prod" ]
			then
				METVIEW_STARTUP="Desktop"
				METVIEW_EXIT="Desktop"
			fi
			;;

		-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
			;;

		*)
			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=dev



case $METVIEW_VERSION in

 dev)
	METVIEW_DIR=${METVIEW_DIR_DEV}
	METVIEW_DIR_SHARE=${METVIEW_DIR_DEV}/share/metview
	METVIEW_BIN=${METVIEW_BIN:=$METVIEW_DIR/bin}
	METV_DEV=yes
	MV_DEBUG_PRINT=${MV_DEBUG_PRINT:=1}
	;;

 prod)
	METVIEW_DIR=$INSTALLDIR
	METVIEW_DIR_SHARE=${METVIEW_DIR}/share/metview
	METVIEW_BIN=${METVIEW_BIN:=$METVIEW_DIR/bin/Metview}
	METV_DEV=no
	;;
esac

METVIEW_LIB=${METVIEW_LIB:=$METVIEW_DIR/lib}

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

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  PWR XCPU  XFSZ"
#           1   2   3    15  19/29 30/24 31/25
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=MetviewUI
METVIEW_EXIT=MetviewUI
METVIEW_FONTS=NormalFonts


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

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

 dev)
   METVIEW_CMD=${METVIEW_CMD:="xterm -iconic -e"}
   #timeout=${METVIEW_TIMEOUT:=60}
   timeout=${METVIEW_TIMEOUT:=240}
   METVIEW_STARTUP=xserv
   METVIEW_EXIT=xserv

   # 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

# =============================================================
# 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
  export GRIB_DEFINITION_PATH="${METVIEW_EXTRA_GRIB_DEFINITION_PATH}:${GRIBAPI_DIR}/share/grib_api/definitions"
fi

# =============================================================
# 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" != "Xnone" ] &&  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="MetviewUI"

#===============================================================
# 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="-style plastique -stylesheet $METVIEW_DIR_SHARE/app-defaults/metview.qss -graphicssystem $METVIEW_GRAPHICS_SYSTEM"

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


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

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


# =============================================================
# 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



# =================
# 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

if [ ! -d "$METVIEW_USER_DIRECTORY/System" ]
then
	metview_create_user_dir "$METVIEW_USER_DIRECTORY"
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)
	    # 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

    METVIEW_PS_VIEWER=${METVIEW_PS_VIEWER:=gv}
    METVIEW_PDF_VIEWER=${METVIEW_PDF_VIEWER:=xpdf}
    METVIEW_PNG_VIEWER=${METVIEW_PNG_VIEWER:=xv}
    METVIEW_JPEG_VIEWER=${METVIEW_JPEG_VIEWER:=xv}
    METVIEW_GIF_VIEWER=${METVIEW_GIF_VIEWER:=display}
    METVIEW_TIFF_VIEWER=${METVIEW_TIFF_VIEWER:=display}
    METVIEW_RASTER_EDITOR=${METVIEW_RASTER_EDITOR:=gimp}
    METVIEW_KML_VIEWER=${METVIEW_KML_VIEWER:=google-earth}

    #########
    # 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 

    resY=`xdpyinfo | grep "resolution" | awk '{print $2}' | cut -d "x" -f 2` 
    METVIEW_SCREEN_RESOLUTION=${METVIEW_SCREEN_RESOLUTION:=$resY}
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

# if $EC_USE_ECREGRID=1 then change the normal Mars client to instead
# be the ecRegrid Mars client
if [ "x$EC_USE_ECREGRID" = x1  ]
then
    echo " *** EC_USE_ECREGRID is $EC_USE_ECREGRID - will use ecRegrid for Mars interpolation ***"
    sed 's/service[ \t]*=[ \t]*mars$/service = marsEcRegrid/g' $METVIEW_TMPDIR/config > $METVIEW_TMPDIR/config_temp
    mv $METVIEW_TMPDIR/config_temp $METVIEW_TMPDIR/config
fi


# ===============================================================
# 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

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
# =============================================================

# no core files
ulimit -c 0

if [ $METVIEW_MODE = batch ]
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_QUIET -startup "\$MACRO_STARTUP"

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

	$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
	else
		$metview_command $METVIEW_BIN/event -startup '$METVIEW_STARTUP ${METVIEW_QT_APPLICATION_FLAGS}' \
			 -exit $METVIEW_EXIT
	fi
fi
