#!/usr/bin/ksh

#
# This file is a part of the NsCDE - Not so Common Desktop Environment
# Author: Hegel3DReloaded
# Licence: GPLv3
#

# Find suitable FvwmCommand on the system which may have this situations:
# fvwm 2x
# fvwm3 in standard path
# fvwm3 in non-standard path
# fvwm2 and fvwm3 on the same system in all possible paths and non-paths
# fvwm2 with fvwm2 as binary name
# fallback if found

# Check if NsCDE FVWM_BIN is set, and try to find FvwmCommand in the same directory.
if [ "x$FVWM_BIN" != "x" ]; then
   FVWM_BASE=${FVWM_BIN%/*}
   if [ -x "${FVWM_BASE}/FvwmCommand" ]; then
      FVWM_CLNT="${FVWM_BASE}/FvwmCommand"
   fi
# If there is no FVWM_BIN set, check if fvwm3 FVWM_IS_FVWM3 is set to 1
# search for fvwm3 binary and try to find FvwmCommand in the same directory.
elif [ "x$FVWM_IS_FVWM3" == "x1" ]; then
   FVWM_FINDBIN=$(whence fvwm3)
   FVWM_BASE=${FVWM_FINDBIN%/*}
   if [ -x "${FVWM_BASE}/FvwmCommand" ]; then
      FVWM_CLNT="${FVWM_BASE}/FvwmCommand"
   fi
# Search for plain "fvwm" name and "fvwm2" if "fvwm" is not found
# try to find FvwmCommand in the same directory.
else
   FVWM_FINDBIN=$(whence fvwm)
   if [ "x$FVWM_FINDBIN" == "x" ]; then
      FVWM_FINDBIN=$(whence fvwm2)
   fi
   FVWM_BASE=${FVWM_FINDBIN%/*}
   if [ -x "${FVWM_BASE}/FvwmCommand" ]; then
      FVWM_CLNT="${FVWM_BASE}/FvwmCommand"
   fi
fi

# Last resort really
if [ "x$FVWM_CLNT" == "x" ]; then
   FVWM_CLNT="FvwmCommand"
fi

# Execute FvwmCommand if found, with all of the argument vector provided
if [ "x$FVWM_CLNT" != "x" ]; then
   exec $FVWM_CLNT "$@"
else
   echo "ERROR: Cannot find suitable FvwmCommand for your setup." >&2
fi

