#!/bin/bash

###############################################################################
# BulmaFact-server instalation script 
# (C) Tomeu Borrás, y René Mérou Septiempbre 2004-2006
# distributed under GPL licence
#------------------------------------------------------------------------------
###############################################################################


version="v0.5.9 - server"
direj="/usr/share/bulmages"
ptexto="--texto"



#creating database users.
echo -e  "\033[33m""Enter a database user for the program (or press enter to stop ussers addition):"  "\033[0m"
read user
while [ "$user" != "" ]
  do
    su - postgres -c "createuser --adduser --createdb $user"
    echo -e  "\033[33m""Enter a database user for the program: (or press enter to stop ussers addition) "  "\033[0m"
    read user
  done



function tiempo {
  sleep 2
}

# root?
if [ ! $(whoami) = "root" ]; then
   echo "This script must be executed like root. \n"
   exit 1
fi

if [ -e /etc/bulmafact-server.conf ]; then
 echo "/etc/bulmafact-server.conf exists, this means the bulmafact database was installed before. "
 LIST_DATABASES=`su - postgres -c "psql -l -t"`
   for database in $LIST_DATABASES
   do
   # info "Procesing databases $database"
   # using patchs for BulmaCont
      for j in `ls /usr/share/bulmages/dbmodels/actualizar | grep rev- | sort 2> /dev/null`
      do
         # info "checking the existence of the file /usr/share/bulmages/$j"
         if [ ! -e /usr/share/bulmages/dbmodels/actualizar/$j ]; then
           # info "checking the tipe of the database $database"
            TIPO=`su - postgres -c "psql -t $database -c \"SELECT valor FROM configuracion WHERE nombre='Tipo'\"" 2> /dev/null`
            if [ "$TIPO" = " bulmafact" ]; then
               echo "upgrading database with patch $direj/$j a $database"
               su - postgres -c "pg_dump $database > /tmp/backup/$database.pgdump"
               su - postgres -c "psql $database < $direj/dbmodels/actualizar/$j > /dev/null" 
               tiempo
            fi
         fi 
      done
   done
else

 echo "Creating databases. \n"
 tiempo
      # Creating databases for BulmaFact.
      su - postgres -c "/usr/share/bulmages/dbmodels/creabulmafact $ptexto bulmafact 2 \"Facturacion Vacia\" 2006 metabd"
      echo "instalation of the new version of configuration file. \n"
      touch /etc/bulmafact-server.conf

   echo "BulmaFact-server installed" "\033[32m" "\033[0m"

fi