#!/bin/bash
###############################################################################
# BulmaCont-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



# installing  databases

echo "Creating databases. \n"
tiempo



if [ -e /etc/bulmacont-server.conf ]; then
 echo "/etc/bulmacont-server.conf exists, this means the bulmacont 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" = " bulmacont" ]; then
	     #info "error: there exist one BulmaCont database"
	     tiempo
  
               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" 
	       #exit 0
	   fi            

         fi
      done
   done
else
      # Creating databases for bulmacont.
      su - postgres -c "/usr/share/bulmages/dbmodels/creabulmacont $ptexto bulmacont 2 BulmaCont 2006"
      su - postgres -c "/usr/share/bulmages/dbmodels/creabulmacont $ptexto bgplangcont 1 \"Plan Contable Vacio\" 2006"
      echo "instalation of the new version of configuration file. \n"
      touch /etc/bulmacont-server.conf
      echo "BulmaCont-server installed" "\033[32m" "\033[0m"

fi
