#!/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
  da)
    lang=dansk.lng
  ;;
  de)
    lang=german.lng
  ;;
  eu)
    lang=euskara.lng
  ;;
  es)
    lang=$(echo español.lng | iconv -f UTF-8 -t ISO-8859-1)
  ;;
  fr)
    lang=francais.lng
  ;;
  gl)
    lang=galego.lng
  ;;
  hu)
    lang=magyar.lng
  ;;
  it)
    lang=italiano.lng
  ;;
  nb|nn)
    lang=norsk.lng
  ;;
  pt)
    lang=pt-BR.lng
  ;;
  tr)
    lang=turkish.lng
  ;;
  gr)
    lang=greek.lng
  ;;
  *)
    lang=english.lng
  ;;
esac

mkdir -p $GLEST_LOCAL_DIR
cd $GLEST_LOCAL_DIR
for dir in techs data maps scenarios tilesets; 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
fi
# servers.ini
[ -e servers.ini ] || cp $GLEST_DATA_DIR/servers.ini .
# launch the game
exec $GLEST_EXECUTABLE "$@"
