#!/bin/ksh
#
# A script to return "linux"     if you're on (any) linux platform
#                    "aix"       if you're on ibm aix platform
#                    "solaris"   if you're on sun solaris platform
#                    "osx"       if you're on apple mac platform
#
# otherwise returns "unknown"
#
# The script uses all available information to figure out the platform
#

set -eu

export ARCH=${ARCH:="unknown"}
export ODB_ARCH=${ODB_ARCH:="$ARCH"}

target=unknown

if [[ -d /cygdrive ]] ; then
  target="cygwin"
fi

#-- target unknown ? Run 'uname' command, if available
if [[ "$target" = "unknown" ]] ; then
  unamecmd=$(whence uname 2>/dev/null || echo "")
  if [[ "$unamecmd" != "" && -x "$unamecmd" ]] ; then
    arch=$($unamecmd | perl -pe 'tr/A-Z/a-z/')
    case "$arch" in
    linux  )   target=linux   ;;
    i*86   )   target=linux   ;;
    x86*   )   target=linux   ;;
    aix    )   target=aix     ;;
    ibm_power* )   target=aix ;;
    sun*   )   target=solaris ;;
    *alpha*)   target=alpha   ;;
    osf*)      target=alpha   ;;
    super-ux*) target=necsx   ;;
    darwin )   target=osx     ;;
    esac
  fi
fi

#-- target still unknown ? Run 'arch' command, if available
if [[ "$target" = "unknown" ]] ; then
  archcmd=$(whence arch 2>/dev/null || echo "")
  if [[ "$archcmd" != "" && -x "$archcmd" ]] ; then
    arch=$($archcmd | perl -pe 'tr/A-Z/a-z/')
    case "$arch" in
    linux  )   target=linux   ;;
    i*86   )   target=linux   ;;
    x86*   )   target=linux   ;;
    aix    )   target=aix     ;;
    ibm_power* )   target=aix ;;
    sun*   )   target=solaris ;;
    *alpha*)   target=alpha   ;;
    esac
  fi
fi

#-- target still unknown ? Use $ODB_ARCH entry
if [[ "$target" = "unknown" ]] ; then
  arch=$(echo "$ODB_ARCH" | perl -pe 'tr/A-Z/a-z/')
  case "$arch" in
  necsx* )   target=necsx   ;;
  linux  )   target=linux   ;;
  i*86   )   target=linux   ;;
  x86*   )   target=linux   ;;
  *g95*  )   target=linux   ;;
  aix    )   target=aix     ;;
  ibm_power* )   target=aix ;;
  sun*   )   target=solaris ;;
  *alpha*)   target=alpha   ;;
  esac
fi

if [[ "$target" = "linux" && "$ODB_ARCH" = @(sun_linux*) ]] ; then
#-- This system uses Sun/Studio compilers ported for Linux !!
  target=solaris
fi

if [[ "$target" = "linux" && "$ODB_ARCH" = @(nectx*) ]] ; then
#-- In essence: export ODB_ARCH=nectx and your target becomes "nectx" (NEC SX front-end)
#   to be used by "odbf90" & "odbcc" scripts instead of "linux"
#-- We could have checked presence of /SX -directory as well, but 
#   then we would never have been able to run anything on NEC TX front-end as "linux"
  target=nectx
fi

if [[ "$target" = "linux" && "$ODB_ARCH" = @(cray_amd|cray_xt*) ]] ; then
#-- Check if Cray XT3/4 catamount
  yod=$(whence yod 2>/dev/null || echo "")
  if [[ "$yod" != "" && -x "$yod" ]] ; then
    target=$(echo "$ODB_ARCH" | cut -c1-8)
  fi
fi

echo "$target"
