#!/bin/sh

. /usr/share/opengl-games-utils/opengl-game-functions.sh
checkDriOK glest

GLEST_LOCAL_DIR=$HOME/.glest
GLEST_DATA_DIR=/usr/share/glest
GLEST_EXECUTABLE=/usr/libexec/glest/glest

tmplang="$LANG"
test "$LC_MESSAGES" != "" && tmplang="$LC_MESSAGES"
test "$LC_ALL"      != "" && tmplang="$LC_ALL"
test "$LANGUAGE"    != "" && tmplang="$LANGUAGE"

lang=`echo $tmplang|cut -d "_" -f 1`

case $lang in
  cz)
    lang=cesky
  ;;
  da)
    lang=dansk
  ;;
  de)
    lang=german
  ;;
  eu)
    lang=euskara
  ;;
  es)
    lang=espanol
  ;;
  fr)
    lang=francais
  ;;
  gl)
    lang=galego
  ;;
  hu)
    lang=magyar
  ;;
  it)
    lang=italian
  ;;
  nb|nn)
    lang=norsk
  ;;
  pt)
    lang=brazilian
  ;;
  tr)
    lang=turkish
  ;;
  gr)
    lang=greek
  ;;
  ru)
    lang=russian
  ;;
  *)
    lang=english
  ;;
esac

mkdir -p $GLEST_LOCAL_DIR
cd $GLEST_LOCAL_DIR
for dir in techs data maps scenarios tilesets tutorials; do
    ln -snf $GLEST_DATA_DIR/$dir $dir
done
test -L screens && rm screens

# glest.ini
if [ ! -e glest.ini ]; then
  X=$(xdpyinfo|grep "dimensions:"|awk '{print $2}'|cut -d "x" -f 1)
  Y=$(xdpyinfo|grep "dimensions:"|awk '{print $2}'|cut -d "x" -f 2)
  sed -e s/ScreenWidth=.*/ScreenWidth=$X/g \
      -e s/ScreenHeight=.*/ScreenHeight=$Y/g \
      $GLEST_DATA_DIR/glest.ini > glest.ini
  if [ -f $GLEST_DATA_DIR/data/lang/$lang ]; then
    sed -i -e s/Lang=.*/Lang=$lang/g glest.ini
  fi
  max_texture_units="`glxinfo -l | awk '/GL_MAX_TEXTURE_UNITS_ARB/ { print $3 }'`"
  if [ -n "$max_texture_units" -a "$max_texture_units" -lt 3 ]; then
    echo "Your video card does not support enough texture units, turning off shadows..."
    sed -i -e "s/Shadows=.*/Shadows=Disabled/g" glest.ini
  fi
else
  # Upgrade the .ini file
  awk -F= '{print $1}' $GLEST_DATA_DIR/glest.ini | grep -v '^;' | while read instruction; do
    [ -n "$instruction" ] || continue
    grep -qs ^$instruction glest.ini || \
      grep ^$instruction $GLEST_DATA_DIR/glest.ini >> glest.ini
  done
  # Remove lang pack extension
  sed -i -e 's/Lang=\(.*\)\.lng/Lang=\1/g' glest.ini
  # Switch to english if the lang file can't be found
  # (instead of aborting without graphical warning)
  curlang=`awk -F= '/^Lang=/ {print $1}' glest.ini`
  if [ ! -f $GLEST_DATA_DIR/data/lang/$curlang.lng ]; then
      sed -i -e s/Lang=.*/Lang=english/g glest.ini
  fi
fi
# servers.ini
[ -e servers.ini ] || cp $GLEST_DATA_DIR/servers.ini .
# launch the game
exec $GLEST_EXECUTABLE "$@"
