#!/bin/bash

CONF_FILE=/etc/eToken.conf
ETOKEN_DEB=SafenetAuthenticationClient-9.1.7-0_amd64.deb
VERSION=9.1.7-0
need_logout=0
lang=pt-BR

set_lang()
{
  INSTALLED_LANG=`grep "LanguageId=" $CONF_FILE`
  if [ "$INSTALLED_LANG" != "LanguageId=$lang" ] ; then
    echo "Installing Language code ${lang}."
    cat ${CONF_FILE} | sed -e "s/LanguageId=[a-z][a-z]-[A-Z][A-Z]/LanguageId=${lang}/" > /tmp/eToken.conf.new
    mv /tmp/eToken.conf.new ${CONF_FILE}
    need_logout=1
  fi
  return 0
}

check_root ()
{
  if [ "$UID" != "0" ] ; then
    echo "Please run this script as root!"
    exit 1
  fi
  return 0
}

check_root

INSTALLED=`dpkg --get-selections | grep -i SafenetAuthenticationClient | awk '{ print $2 } '`
if [ "$INSTALLED" != "install" ]  ; then
  if [ -f $ETOKEN_DEB ] ; then
    if ! dpkg -i $ETOKEN_DEB ; then
      apt-get install --fix-broken --yes
      if ! dpkg -i $ETOKEN_DEB ; then
        echo "deb package installation failed."
        exit 1
      fi
    fi
    need_logout=1
  else
    echo "installation file $ETOKEN_DEB missing."
    exit 1
  fi
else
  VERSION_INSTALLED=`dpkg -l | grep -i SafenetAuthenticationClient | awk  '{ print $3 } '`
  if [ "$VERSION" != "$VERSION_INSTALLED" ] ; then
    if [ -f $ETOKEN_DEB ] ; then
      if ! dpkg -i $ETOKEN_DEB ; then
        echo "deb package upgrade failed."
        exit 1
      fi
      need_logout=1
    else
      echo "installation file $ETOKEN_DEB missing."
      exit 1
    fi
  fi
fi

set_lang

if [ $need_logout = 1 ] ; then
    echo "logout and login to apply changes"
fi



