source: installer/opengnsys_installer.sh @ e1ddc83

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacionwebconsole3
Last change on this file since e1ddc83 was de1220c, checked in by ramon <ramongomez@…>, 11 years ago

#616: Instalar usando ogLive 1.0.4.

git-svn-id: https://opengnsys.es/svn/branches/version1.0@4156 a21b9725-9963-47de-94b9-378ad31fedc9

  • Property mode set to 100755
File size: 53.7 KB
Line 
1#!/bin/bash
2
3#####################################################################
4####### Script instalador OpenGnSys
5####### autor: Luis Guillén <lguillen@unizar.es>
6#####################################################################
7
8
9####  AVISO: Puede editar configuración de acceso por defecto.
10####  WARNING: Edit default access configuration if you wish.
11DEFAULT_MYSQL_ROOT_PASSWORD="passwordroot"      # Clave por defecto root de MySQL
12DEFAULT_OPENGNSYS_DB_USER="usuog"                   # Usuario por defecto de acceso a la base de datos
13DEFAULT_OPENGNSYS_DB_PASSWD="passusuog"         # Clave por defecto de acceso a la base de datos
14DEFAULT_OPENGNSYS_CLIENT_PASSWD="og"            # Clave por defecto de acceso del cliente       
15
16# Sólo ejecutable por usuario root
17if [ "$(whoami)" != 'root' ]; then
18        echo "ERROR: this program must run under root privileges!!"
19        exit 1
20fi
21
22echo -e "\\nOpenGnSys Installation"
23echo "=============================="
24
25# Clave root de MySQL
26while : ; do
27        echo -n -e "\\nEnter root password for MySQL (${DEFAULT_MYSQL_ROOT_PASSWORD}): ";
28        read MYSQL_ROOT_PASSWORD
29        if [ -n "${MYSQL_ROOT_PASSWORD//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico
30                echo -e "\\aERROR: Must be alphanumeric, try again..."
31        else
32                if [ -z $MYSQL_ROOT_PASSWORD ]; then # Si esta vacio ponemos el valor por defecto
33                        MYSQL_ROOT_PASSWORD=$DEFAULT_MYSQL_ROOT_PASSWORD
34                fi
35                break
36        fi
37done
38
39# Usuario de acceso a la base de datos
40while : ; do
41        echo -n -e "\\nEnter username for OpenGnSys console (${DEFAULT_OPENGNSYS_DB_USER}): "
42        read OPENGNSYS_DB_USER
43        if [ -n "${OPENGNSYS_DB_USER//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico
44                echo -e "\\aERROR: Must be alphanumeric, try again..."
45        else
46                if [ -z $OPENGNSYS_DB_USER ]; then # Si esta vacio ponemos el valor por defecto
47                        OPENGNSYS_DB_USER=$DEFAULT_OPENGNSYS_DB_USER
48                fi
49                break
50        fi
51done
52
53# Clave de acceso a la base de datos
54while : ; do
55        echo -n -e "\\nEnter password for OpenGnSys console (${DEFAULT_OPENGNSYS_DB_PASSWD}): "
56        read OPENGNSYS_DB_PASSWD
57        if [ -n "${OPENGNSYS_DB_PASSWD//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico
58                echo -e "\\aERROR: Must be alphanumeric, try again..."
59        else
60                if [ -z $OPENGNSYS_DB_PASSWD ]; then # Si esta vacio ponemos el valor por defecto
61                        OPENGNSYS_DB_PASSWD=$DEFAULT_OPENGNSYS_DB_PASSWD
62                fi
63                break
64        fi
65done
66
67# Clave de acceso del cliente
68while : ; do
69        echo -n -e "\\nEnter root password for OpenGnSys client (${DEFAULT_OPENGNSYS_CLIENT_PASSWD}): "
70        read OPENGNSYS_CLIENT_PASSWD
71        if [ -n "${OPENGNSYS_CLIENT_PASSWD//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico
72                echo -e "\\aERROR: Must be alphanumeric, try again..."
73        else
74                if [ -z $OPENGNSYS_CLIENT_PASSWD ]; then # Si esta vacio ponemos el valor por defecto
75                        OPENGNSYS_CLIENT_PASSWD=$DEFAULT_OPENGNSYS_CLIENT_PASSWD
76                fi
77                break
78        fi
79done
80
81echo -e "\\n=============================="
82
83# Comprobar si se ha descargado el paquete comprimido (USESVN=0) o sólo el instalador (USESVN=1).
84PROGRAMDIR=$(readlink -e $(dirname "$0"))
85PROGRAMNAME=$(basename "$0")
86OPENGNSYS_SERVER="www.opengnsys.es"
87if [ -d "$PROGRAMDIR/../installer" ]; then
88        USESVN=0
89else
90        USESVN=1
91fi
92SVN_URL="http://$OPENGNSYS_SERVER/svn/branches/version1.0/"
93
94WORKDIR=/tmp/opengnsys_installer
95mkdir -p $WORKDIR
96
97# Directorio destino de OpenGnSys.
98INSTALL_TARGET=/opt/opengnsys
99
100# Registro de incidencias.
101OGLOGFILE=$INSTALL_TARGET/log/${PROGRAMNAME%.sh}.log
102LOG_FILE=/tmp/$(basename $OGLOGFILE)
103
104# Usuario del cliente para acceso remoto.
105OPENGNSYS_CLIENT_USER="opengnsys"
106
107# Nombre de la base datos y fichero SQL para su creación.
108OPENGNSYS_DATABASE="ogAdmBD"
109OPENGNSYS_DB_CREATION_FILE=opengnsys/admin/Database/${OPENGNSYS_DATABASE}.sql
110
111
112#####################################################################
113####### Funciones de configuración
114#####################################################################
115
116# Generar variables de configuración del instalador
117# Variables globales:
118# - OSDISTRIB, OSCODENAME - datos de la distribución Linux
119# - DEPENDENCIES - array de dependencias que deben estar instaladas
120# - UPDATEPKGLIST, INSTALLPKGS, CHECKPKGS - comandos para gestión de paquetes
121# - INSTALLEXTRADEPS - instalar dependencias no incluidas en la distribución
122# - STARTSERVICE, ENABLESERVICE - iniciar y habilitar un servicio
123# - STOPSERVICE, DISABLESERVICE - parar y deshabilitar un servicio
124# - APACHESERV, APACHECFGDIR, APACHESITESDIR, APACHEUSER, APACHEGROUP - servicio y configuración de Apache
125# - APACHESSLMOD, APACHEENABLESSL, APACHEMAKECERT - habilitar módulo Apache y certificado SSL
126# - APACHEENABLEOG, APACHEOGSITE, - habilitar sitio web de OpenGnSys
127# - INETDSERV - servicio Inetd
128# - IPTABLESSERV - servicio IPTables
129# - DHCPSERV, DHCPCFGDIR - servicio y configuración de DHCP
130# - MYSQLSERV, TMPMYCNF - servicio MySQL y fichero temporal con credenciales de acceso.
131# - RSYNCSERV, RSYNCCFGDIR - servicio y configuración de Rsync
132# - SAMBASERV, SAMBACFGDIR - servicio y configuración de Samba
133# - TFTPSERV, TFTPCFGDIR, SYSLINUXDIR - servicio y configuración de TFTP/PXE
134function autoConfigure()
135{
136# Detectar sistema operativo del servidor (debe soportar LSB).
137OSDISTRIB=$(lsb_release -is 2>/dev/null)
138OSCODENAME=$(lsb_release -cs 2>/dev/null)
139
140# Configuración según la distribución GNU/Linux.
141case "$OSDISTRIB" in
142        Ubuntu|Debian|LinuxMint)
143                DEPENDENCIES=( subversion apache2 php5 php5-ldap libapache2-mod-php5 mysql-server php5-mysql isc-dhcp-server bittorrent tftp-hpa tftpd-hpa syslinux xinetd build-essential g++-multilib libmysqlclient15-dev wget doxygen graphviz bittornado ctorrent samba rsync unzip netpipes debootstrap schroot squashfs-tools btrfs-tools )
144                UPDATEPKGLIST="apt-get update"
145                INSTALLPKG="apt-get -y install --force-yes"
146                CHECKPKG="dpkg -s \$package 2>/dev/null | grep Status | grep -qw install"
147                if which service &>/dev/null; then
148                        STARTSERVICE="eval service \$service restart"
149                        STOPSERVICE="eval service \$service stop"
150                else
151                        STARTSERVICE="eval /etc/init.d/\$service restart"
152                        STOPSERVICE="eval /etc/init.d/\$service stop"
153                fi
154                ENABLESERVICE="eval update-rc.d \$service defaults"
155                DISABLESERVICE="eval update-rc.d \$service disable"
156                APACHESERV=apache2
157                APACHECFGDIR=/etc/apache2
158                APACHESITESDIR=sites-available
159                APACHEOGSITE=opengnsys
160                APACHEUSER="www-data"
161                APACHEGROUP="www-data"
162                APACHESSLMOD="a2enmod ssl"
163                APACHEENABLESSL="a2ensite default-ssl"
164                APACHEENABLEOG="a2ensite $APACHEOGSITE"
165                APACHEMAKECERT="make-ssl-cert generate-default-snakeoil --force-overwrite"
166                DHCPSERV=isc-dhcp-server
167                DHCPCFGDIR=/etc/dhcp
168                INETDSERV=xinetd
169                INETDCFGDIR=/etc/xinetd.d
170                MYSQLSERV=mysql
171                RSYNCSERV=rsync
172                RSYNCCFGDIR=/etc
173                SAMBASERV=smbd
174                SAMBACFGDIR=/etc/samba
175                SYSLINUXDIR=/usr/lib/syslinux
176                TFTPCFGDIR=/var/lib/tftpboot
177                ;;
178        Fedora|CentOS)
179                DEPENDENCIES=( subversion httpd mod_ssl php php-ldap mysql-server mysql-devel mysql-devel.i686 php-mysql dhcp tftp-server tftp syslinux xinetd binutils gcc gcc-c++ glibc-devel glibc-devel.i686 glibc-static glibc-static.i686 libstdc++ libstdc++.i686 libstdc++-static.i686 libstdc++-devel.i686 make wget doxygen graphviz ctorrent samba rsync unzip debootstrap schroot squashfs-tools btrfs-progs )
180                INSTALLEXTRADEPS=( 'rpm -Uv ftp://ftp.altlinux.org/pub/distributions/ALTLinux/5.1/branch/files/i586/RPMS/netpipes-4.2-alt1.i586.rpm'
181                                   'pushd /tmp; wget http://download.bittornado.com/download/BitTornado-0.3.18.tar.gz; tar xvzf BitTornado-0.3.18.tar.gz; cd BitTornado-CVS; python setup.py install; ln -fs btlaunchmany.py /usr/bin/btlaunchmany; ln -fs bttrack.py /usr/bin/bttrack; popd' )
182                if [ "$OSDISTRIB" == "CentOS" ]; then
183                        UPDATEPKGLIST='test rpm -q --quiet epel-release || echo -e "[epel]\nname=EPEL temporal\nmirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-\$releasever&arch=\$basearch\nenabled=1\ngpgcheck=0" >/etc/yum.repos.d/epel.repo'
184                fi
185                INSTALLPKG="yum install -y"
186                CHECKPKG="rpm -q --quiet \$package"
187                SYSTEMD=$(which systemctl 2>/dev/null)
188                if [ -n "$SYSTEMD" ]; then
189                        STARTSERVICE="eval systemctl start \$service.service"
190                        STOPSERVICE="eval systemctl stop \$service.service"
191                        ENABLESERVICE="eval systemctl enable \$service.service"
192                        DISABLESERVICE="eval systemctl disable \$service.service"
193                else
194                        STARTSERVICE="eval service \$service start"
195                        STOPSERVICE="eval service \$service stop"
196                        ENABLESERVICE="eval chkconfig \$service on"
197                        DISABLESERVICE="eval chkconfig \$service off"
198                fi
199                APACHESERV=httpd
200                APACHECFGDIR=/etc/httpd/conf.d
201                APACHEOGSITE=opengnsys.conf
202                APACHEUSER="apache"
203                APACHEGROUP="apache"
204                DHCPSERV=dhcpd
205                DHCPCFGDIR=/etc/dhcp
206                INETDSERV=xinetd
207                INETDCFGDIR=/etc/xinetd.d
208                IPTABLESSERV=iptables
209                MYSQLSERV=mysqld
210                RSYNCSERV=rsync
211                RSYNCCFGDIR=/etc
212                SAMBASERV=smb
213                SAMBACFGDIR=/etc/samba
214                SYSLINUXDIR=/usr/share/syslinux
215                TFTPSERV=tftp
216                TFTPCFGDIR=/var/lib/tftpboot
217                ;;
218        "")     echo "ERROR: Unknown Linux distribution, please install \"lsb_release\" command."
219                exit 1 ;;
220        *)      echo "ERROR: Distribution not supported by OpenGnSys."
221                exit 1 ;;
222esac
223
224# Fichero de credenciales de acceso a MySQL.
225TMPMYCNF=/tmp/.my.cnf.$$
226}
227
228# Modificar variables de configuración tras instalar paquetes del sistema.
229function autoConfigurePost()
230{
231[ -z "$SYSTEMD" -a ! -e /etc/init.d/$SAMBASERV ] && SAMBASERV=samba     # Debian 6
232[ ! -e $TFTPCFGDIR ] && TFTPCFGDIR=/srv/tftp            # Debian 6
233[ -f /selinux/enforce ] && echo 0 > /selinux/enforce    # SELinux permisivo
234selinuxenabled && setenforce 0 2>/dev/null              # SELinux permisivo (Fedora 17)
235}
236
237
238# Cargar lista de paquetes del sistema y actualizar algunas variables de configuración
239# dependiendo de la versión instalada.
240function updatePackageList()
241{
242local DHCPVERSION
243
244# Si es necesario, actualizar la lista de paquetes disponibles.
245[ -n "$UPDATEPKGLIST" ] && eval $UPDATEPKGLIST
246
247# Configuración personallizada de algunos paquetes.
248case "$OSDISTRIB" in
249        Ubuntu|LinuxMint)       # Postconfiguación personalizada para Ubuntu.
250                # Configuración para DHCP v3.
251                DHCPVERSION=$(apt-cache show $(apt-cache pkgnames|egrep "dhcp.?-server$") | \
252                              awk '/Version/ {print substr($2,1,1);}' | \
253                              sort -n | tail -1)
254                if [ $DHCPVERSION = 3 ]; then
255                        DEPENDENCIES=( ${DEPENDENCIES[@]/isc-dhcp-server/dhcp3-server} )
256                        DHCPSERV=dhcp3-server
257                        DHCPCFGDIR=/etc/dhcp3
258                fi
259                ;;
260        CentOS) # Postconfiguación personalizada para CentOS.
261                # Incluir repositorio de paquetes EPEL.
262                DEPENDENCIES=( ${DEPENDENCIES[@]} epel-release )
263                ;;
264esac
265}
266
267
268#####################################################################
269####### Algunas funciones útiles de propósito general:
270#####################################################################
271
272function getDateTime()
273{
274        date "+%Y%m%d-%H%M%S"
275}
276
277# Escribe a fichero y muestra por pantalla
278function echoAndLog()
279{
280        local DATETIME=`getDateTime`
281        echo "$1"
282        echo "$DATETIME;$SSH_CLIENT;$1" >> $LOG_FILE
283}
284
285# Escribe a fichero y muestra mensaje de error
286function errorAndLog()
287{
288        local DATETIME=`getDateTime`
289        echo "ERROR: $1"
290        echo "$DATETIME;$SSH_CLIENT;ERROR: $1" >> $LOG_FILE
291}
292
293# Comprueba si el elemento pasado en $2 está en el array $1
294function isInArray()
295{
296        if [ $# -ne 2 ]; then
297                errorAndLog "${FUNCNAME}(): invalid number of parameters"
298                exit 1
299        fi
300
301        local deps
302        local is_in_array=1
303        local element="$2"
304
305        echoAndLog "${FUNCNAME}(): checking if $2 is in $1"
306        eval "deps=( \"\${$1[@]}\" )"
307
308        # Copia local del array del parámetro 1.
309        for (( i = 0 ; i < ${#deps[@]} ; i++ )); do
310                if [ "${deps[$i]}" = "${element}" ]; then
311                        echoAndLog "isInArray(): $element found in array"
312                        is_in_array=0
313                fi
314        done
315
316        if [ $is_in_array -ne 0 ]; then
317                echoAndLog "${FUNCNAME}(): $element NOT found in array"
318        fi
319
320        return $is_in_array
321}
322
323
324#####################################################################
325####### Funciones de manejo de paquetes Debian
326#####################################################################
327
328function checkPackage()
329{
330        package=$1
331        if [ -z $package ]; then
332                errorAndLog "${FUNCNAME}(): parameter required"
333                exit 1
334        fi
335        echoAndLog "${FUNCNAME}(): checking if package $package exists"
336        eval $CHECKPKG
337        if [ $? -eq 0 ]; then
338                echoAndLog "${FUNCNAME}(): package $package exists"
339                return 0
340        else
341                echoAndLog "${FUNCNAME}(): package $package doesn't exists"
342                return 1
343        fi
344}
345
346# Recibe array con dependencias
347# por referencia deja un array con las dependencias no resueltas
348# devuelve 1 si hay alguna dependencia no resuelta
349function checkDependencies()
350{
351        if [ $# -ne 2 ]; then
352                errorAndLog "${FUNCNAME}(): invalid number of parameters"
353                exit 1
354        fi
355
356        echoAndLog "${FUNCNAME}(): checking dependences"
357        uncompletedeps=0
358
359        # copia local del array del parametro 1
360        local deps
361        eval "deps=( \"\${$1[@]}\" )"
362
363        declare -a local_notinstalled
364
365        for (( i = 0 ; i < ${#deps[@]} ; i++ ))
366        do
367                checkPackage ${deps[$i]}
368                if [ $? -ne 0 ]; then
369                        local_notinstalled[$uncompletedeps]=$package
370                        let uncompletedeps=uncompletedeps+1
371                fi
372        done
373
374        # relleno el array especificado en $2 por referencia
375        for (( i = 0 ; i < ${#local_notinstalled[@]} ; i++ ))
376        do
377                eval "${2}[$i]=${local_notinstalled[$i]}"
378        done
379
380        # retorna el numero de paquetes no resueltos
381        echoAndLog "${FUNCNAME}(): dependencies uncompleted: $uncompletedeps"
382        return $uncompletedeps
383}
384
385# Recibe un array con las dependencias y lo instala
386function installDependencies()
387{
388        if [ $# -ne 1 ]; then
389                errorAndLog "${FUNCNAME}(): invalid number of parameters"
390                exit 1
391        fi
392        echoAndLog "${FUNCNAME}(): installing uncompleted dependencies"
393
394        # copia local del array del parametro 1
395        local deps
396        eval "deps=( \"\${$1[@]}\" )"
397
398        local string_deps=""
399        for (( i = 0 ; i < ${#deps[@]} ; i++ ))
400        do
401                string_deps="$string_deps ${deps[$i]}"
402        done
403
404        if [ -z "${string_deps}" ]; then
405                errorAndLog "${FUNCNAME}(): array of dependeces is empty"
406                exit 1
407        fi
408
409        OLD_DEBIAN_FRONTEND=$DEBIAN_FRONTEND            # Debian/Ubuntu
410        export DEBIAN_FRONTEND=noninteractive
411
412        echoAndLog "${FUNCNAME}(): now $string_deps will be installed"
413        eval $INSTALLPKG $string_deps
414        if [ $? -ne 0 ]; then
415                errorAndLog "${FUNCNAME}(): error installing dependencies"
416                return 1
417        fi
418
419        DEBIAN_FRONTEND=$OLD_DEBIAN_FRONTEND            # Debian/Ubuntu
420        test grep -q "EPEL temporal" /etc/yum.repos.d/epel.repo 2>/dev/null ] || mv -f /etc/yum.repos.d/epel.repo.rpmnew /etc/yum.repos.d/epel.repo 2>/dev/null # CentOS/RedHat EPEL
421
422        echoAndLog "${FUNCNAME}(): dependencies installed"
423}
424
425# Hace un backup del fichero pasado por parámetro
426# deja un -last y uno para el día
427function backupFile()
428{
429        if [ $# -ne 1 ]; then
430                errorAndLog "${FUNCNAME}(): invalid number of parameters"
431                exit 1
432        fi
433
434        local file="$1"
435        local dateymd=`date +%Y%m%d`
436
437        if [ ! -f "$file" ]; then
438                errorAndLog "${FUNCNAME}(): file $file doesn't exists"
439                return 1
440        fi
441
442        echoAndLog "${FUNCNAME}(): making $file backup"
443
444        # realiza una copia de la última configuración como last
445        cp -a "$file" "${file}-LAST"
446
447        # si para el día no hay backup lo hace, sino no
448        if [ ! -f "${file}-${dateymd}" ]; then
449                cp -a "$file" "${file}-${dateymd}"
450        fi
451
452        echoAndLog "${FUNCNAME}(): $file backup success"
453}
454
455#####################################################################
456####### Funciones para el manejo de bases de datos
457#####################################################################
458
459# This function set password to root
460function mysqlSetRootPassword()
461{
462        if [ $# -ne 1 ]; then
463                errorAndLog "${FUNCNAME}(): invalid number of parameters"
464                exit 1
465        fi
466
467        local root_mysql="$1"
468        echoAndLog "${FUNCNAME}(): setting root password in MySQL server"
469        mysqladmin -u root password "$root_mysql"
470        if [ $? -ne 0 ]; then
471                errorAndLog "${FUNCNAME}(): error while setting root password in MySQL server"
472                return 1
473        fi
474        echoAndLog "${FUNCNAME}(): root password saved!"
475        return 0
476}
477
478# Si el servicio mysql esta ya instalado cambia la variable de la clave del root por la ya existente
479function mysqlGetRootPassword()
480{
481        local pass_mysql
482        local pass_mysql2
483        # Comprobar si MySQL está instalado con la clave de root por defecto.
484        if mysql -u root -p"$MYSQL_ROOT_PASSWORD" <<<"quit" 2>/dev/null; then
485                echoAndLog "${FUNCNAME}(): Using default mysql root password."
486        else
487                stty -echo
488                echo "There is a MySQL service already installed."
489                read -p "Enter MySQL root password: " pass_mysql
490                echo ""
491                read -p "Confrim password:" pass_mysql2
492                echo ""
493                stty echo
494                if [ "$pass_mysql" == "$pass_mysql2" ] ;then
495                        MYSQL_ROOT_PASSWORD="$pass_mysql"
496                        return 0
497                else
498                        echo "The keys don't match. Do not configure the server's key,"
499                        echo "transactions in the database will give error."
500                        return 1
501                fi
502        fi
503}
504
505# comprueba si puede conectar con mysql con el usuario root
506function mysqlTestConnection()
507{
508        if [ $# -ne 1 ]; then
509                errorAndLog "${FUNCNAME}(): invalid number of parameters"
510                exit 1
511        fi
512
513        local root_password="$1"
514        echoAndLog "${FUNCNAME}(): checking connection to mysql..."
515        # Componer fichero con credenciales de conexión a MySQL.
516        touch $TMPMYCNF
517        chmod 600 $TMPMYCNF
518        cat << EOT > $TMPMYCNF
519[client]
520user=root
521password=$root_password
522EOT
523        # Borrar el fichero temporal si termina el proceso de instalación.
524        trap "rm -f $TMPMYCNF" 0 1 2 3 6 9 15
525        # Comprobar conexión a MySQL.
526        echo "" | mysql --defaults-extra-file=$TMPMYCNF
527        if [ $? -ne 0 ]; then
528                errorAndLog "${FUNCNAME}(): connection to mysql failed, check root password and if daemon is running!"
529                return 1
530        else
531                echoAndLog "${FUNCNAME}(): connection success"
532                return 0
533        fi
534}
535
536# comprueba si la base de datos existe
537function mysqlDbExists()
538{
539        if [ $# -ne 1 ]; then
540                errorAndLog "${FUNCNAME}(): invalid number of parameters"
541                exit 1
542        fi
543
544        local database="$1"
545        echoAndLog "${FUNCNAME}(): checking if $database exists..."
546        echo "show databases" | mysql --defaults-extra-file=$TMPMYCNF | grep "^${database}$"
547        if [ $? -ne 0 ]; then
548                echoAndLog "${FUNCNAME}():database $database doesn't exists"
549                return 1
550        else
551                echoAndLog "${FUNCNAME}():database $database exists"
552                return 0
553        fi
554}
555
556function mysqlCheckDbIsEmpty()
557{
558        if [ $# -ne 1 ]; then
559                errorAndLog "${FUNCNAME}(): invalid number of parameters"
560                exit 1
561        fi
562
563        local database="$1"
564        echoAndLog "${FUNCNAME}(): checking if $database is empty..."
565        num_tablas=`echo "show tables" | mysql --defaults-extra-file=$TMPMYCNF "${database}" | wc -l`
566        if [ $? -ne 0 ]; then
567                errorAndLog "${FUNCNAME}(): error executing query, check database and root password"
568                exit 1
569        fi
570
571        if [ $num_tablas -eq 0 ]; then
572                echoAndLog "${FUNCNAME}():database $database is empty"
573                return 0
574        else
575                echoAndLog "${FUNCNAME}():database $database has tables"
576                return 1
577        fi
578
579}
580
581
582function mysqlImportSqlFileToDb()
583{
584        if [ $# -ne 2 ]; then
585                errorAndLog "${FNCNAME}(): invalid number of parameters"
586                exit 1
587        fi
588
589        local database="$1"
590        local sqlfile="$2"
591        local tmpfile=$(mktemp)
592        local i=0
593        local dev=""
594        local status
595
596        if [ ! -f $sqlfile ]; then
597                errorAndLog "${FUNCNAME}(): Unable to locate $sqlfile!!"
598                return 1
599        fi
600
601        echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..."
602        chmod 600 $tmpfile
603        for dev in ${DEVICE[*]}; do
604                if [ "${DEVICE[i]}" == "$DEFAULTDEV" ]; then
605                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
606                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
607                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
608                                $sqlfile > $tmpfile
609                fi
610                let i++
611        done
612        mysql --defaults-extra-file=$TMPMYCNF --default-character-set=utf8 "${database}" < $tmpfile
613        status=$?
614        rm -f $tmpfile
615        if [ $status -ne 0 ]; then
616                errorAndLog "${FUNCNAME}(): error while importing $sqlfile in database $database"
617                return 1
618        fi
619        echoAndLog "${FUNCNAME}(): file imported to database $database"
620        return 0
621}
622
623# Crea la base de datos
624function mysqlCreateDb()
625{
626        if [ $# -ne 1 ]; then
627                errorAndLog "${FUNCNAME}(): invalid number of parameters"
628                exit 1
629        fi
630
631        local database="$1"
632
633        echoAndLog "${FUNCNAME}(): creating database..."
634        mysqladmin --defaults-extra-file=$TMPMYCNF create $database
635        if [ $? -ne 0 ]; then
636                errorAndLog "${FUNCNAME}(): error while creating database $database"
637                return 1
638        fi
639        echoAndLog "${FUNCNAME}(): database $database created"
640        return 0
641}
642
643
644function mysqlCheckUserExists()
645{
646        if [ $# -ne 1 ]; then
647                errorAndLog "${FUNCNAME}(): invalid number of parameters"
648                exit 1
649        fi
650
651        local userdb="$1"
652
653        echoAndLog "${FUNCNAME}(): checking if $userdb exists..."
654        echo "select user from user where user='${userdb}'\\G" |mysql --defaults-extra-file=$TMPMYCNF mysql | grep user
655        if [ $? -ne 0 ]; then
656                echoAndLog "${FUNCNAME}(): user doesn't exists"
657                return 1
658        else
659                echoAndLog "${FUNCNAME}(): user already exists"
660                return 0
661        fi
662
663}
664
665# Crea un usuario administrativo para la base de datos
666function mysqlCreateAdminUserToDb()
667{
668        if [ $# -ne 3 ]; then
669                errorAndLog "${FUNCNAME}(): invalid number of parameters"
670                exit 1
671        fi
672
673        local database="$1"
674        local userdb="$2"
675        local passdb="$3"
676
677        echoAndLog "${FUNCNAME}(): creating admin user ${userdb} to database ${database}"
678
679        cat > $WORKDIR/create_${database}.sql <<EOF
680GRANT USAGE ON *.* TO '${userdb}'@'localhost' IDENTIFIED BY '${passdb}' ;
681GRANT ALL PRIVILEGES ON ${database}.* TO '${userdb}'@'localhost' WITH GRANT OPTION ;
682FLUSH PRIVILEGES ;
683EOF
684        mysql --defaults-extra-file=$TMPMYCNF < $WORKDIR/create_${database}.sql
685        if [ $? -ne 0 ]; then
686                errorAndLog "${FUNCNAME}(): error while creating user in mysql"
687                rm -f $WORKDIR/create_${database}.sql
688                return 1
689        else
690                echoAndLog "${FUNCNAME}(): user created ok"
691                rm -f $WORKDIR/create_${database}.sql
692                return 0
693        fi
694}
695
696
697#####################################################################
698####### Funciones para el manejo de Subversion
699#####################################################################
700
701function svnExportCode()
702{
703        if [ $# -ne 1 ]; then
704                errorAndLog "${FUNCNAME}(): invalid number of parameters"
705                exit 1
706        fi
707
708        local url="$1"
709
710        echoAndLog "${FUNCNAME}(): downloading subversion code..."
711
712        svn export --force "$url" opengnsys
713        if [ $? -ne 0 ]; then
714                errorAndLog "${FUNCNAME}(): error getting OpenGnSys code from $url"
715                return 1
716        fi
717        echoAndLog "${FUNCNAME}(): subversion code downloaded"
718        return 0
719}
720
721
722############################################################
723###  Detectar red
724############################################################
725
726# Comprobar si existe conexión.
727function checkNetworkConnection()
728{
729        echoAndLog "${FUNCNAME}(): Disabling IPTables."
730        if [ -n "$IPTABLESSERV" ]; then
731                service=$IPTABLESSERV
732                $STOPSERVICE; $DISABLESERVICE
733        fi
734
735        echoAndLog "${FUNCNAME}(): Checking OpenGnSys server conectivity."
736        OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"www.opengnsys.es"}
737        wget --spider -q $OPENGNSYS_SERVER
738}
739
740# Obtener los parámetros de red de la interfaz por defecto.
741function getNetworkSettings()
742{
743        # Arrays globales definidas:
744        # - DEVICE:     nombres de dispositivos de red activos.
745        # - SERVERIP:   IPs locales del servidor.
746        # - NETIP:      IPs de redes.
747        # - NETMASK:    máscaras de red.
748        # - NETBROAD:   IPs de difusión de redes.
749        # - ROUTERIP:   IPs de routers.
750        # Otras variables globales:
751        # - DEFAULTDEV: dispositivo de red por defecto.
752        # - DNSIP:      IP del servidor DNS principal.
753
754        local i=0
755        local dev=""
756
757        echoAndLog "${FUNCNAME}(): Detecting network parameters."
758        DEVICE=( $(ip -o link show up | awk '!/loopback/ {sub(/:.*/,"",$2); print $2}') )
759        if [ -z "$DEVICE" ]; then
760                errorAndLog "${FUNCNAME}(): Network devices not detected."
761                exit 1
762        fi
763        for dev in ${DEVICE[*]}; do
764                SERVERIP[i]=$(ip -o addr show dev $dev | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4)}')
765                if [ -n "${SERVERIP[i]}" ]; then
766                        NETMASK[i]=$(LANG=C ifconfig $dev | \
767                                                awk '/Mask/ {sub(/.*:/,"",$4); print $4}
768                                                     /netmask/ {print $4}')
769                        NETBROAD[i]=$(ip -o addr show dev $dev | awk '$3~/inet$/ {print ($6)}')
770                        NETIP[i]=$(netstat -nr | awk -v d="$dev" '$1!~/0\.0\.0\.0/&&$8==d {if (n=="") n=$1} END {print n}')
771                        ROUTERIP[i]=$(netstat -nr | awk -v d="$dev" '$1~/0\.0\.0\.0/&&$8==d {print $2}')
772                        DEFAULTDEV=${DEFAULTDEV:-"$dev"}
773                fi
774                let i++
775        done
776        DNSIP=$(awk '/nameserver/ {print $2}' /etc/resolv.conf | head -n1)
777        if [ -z "${NETIP[*]}" -o -z "${NETMASK[*]}" ]; then
778                errorAndLog "${FUNCNAME}(): Network not detected."
779                exit 1
780        fi
781
782        # Variables de ejecución de Apache
783        # - APACHE_RUN_USER
784        # - APACHE_RUN_GROUP
785        if [ -f $APACHECFGDIR/envvars ]; then
786                source $APACHECFGDIR/envvars
787        fi
788        APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
789        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
790
791        echoAndLog "${FUNCNAME}(): Default network device: $DEFAULTDEV."
792}
793
794
795############################################################
796### Esqueleto para el Servicio pxe y contenedor tftpboot ###
797############################################################
798
799function tftpConfigure()
800{
801        echoAndLog "${FUNCNAME}(): Configuring TFTP service."
802        # Habilitar TFTP y reiniciar Inetd.
803        if [ -n "$TFTPSERV" ]; then
804                service=$TFTPSERV
805                $ENABLESERVICE
806        fi
807        service=$INETDSERV
808        $ENABLESERVICE; $STARTSERVICE
809
810        # preparacion contenedor tftpboot
811        cp -a $SYSLINUXDIR $TFTPCFGDIR/syslinux
812        cp -a $SYSLINUXDIR/pxelinux.0 $TFTPCFGDIR
813        # prepamos el directorio de la configuracion de pxe
814        mkdir -p $TFTPCFGDIR/pxelinux.cfg
815        cat > $TFTPCFGDIR/pxelinux.cfg/default <<EOF
816DEFAULT syslinux/vesamenu.c32
817MENU TITLE Aplicacion GNSYS
818 
819LABEL 1
820MENU LABEL 1
821KERNEL syslinux/chain.c32
822APPEND hd0
823 
824PROMPT 0
825TIMEOUT 10
826EOF
827        # comprobamos el servicio tftp
828        sleep 1
829        testPxe
830}
831
832function testPxe ()
833{
834        echoAndLog "${FUNCNAME}(): Checking TFTP service... please wait."
835        pushd /tmp
836        tftp -v localhost -c get pxelinux.0 /tmp/pxelinux.0 && echoAndLog "TFTP service is OK." || errorAndLog "TFTP service is down."
837        popd
838}
839
840
841########################################################################
842## Configuracion servicio NFS
843########################################################################
844
845# Configurar servicio NFS.
846# ADVERTENCIA: usa variables globales NETIP y NETMASK!
847function nfsConfigure()
848{
849        echoAndLog "${FUNCNAME}(): Config nfs server."
850        backupFile /etc/exports
851
852        nfsAddExport $INSTALL_TARGET/client ${NETIP}/${NETMASK}:ro,no_subtree_check,no_root_squash,sync
853        if [ $? -ne 0 ]; then
854                errorAndLog "${FUNCNAME}(): error while adding NFS client config"
855                return 1
856        fi
857
858        nfsAddExport $INSTALL_TARGET/images ${NETIP}/${NETMASK}:rw,no_subtree_check,no_root_squash,sync,crossmnt
859        if [ $? -ne 0 ]; then
860                errorAndLog "${FUNCNAME}(): error while adding NFS images config"
861                return 1
862        fi
863
864        nfsAddExport $INSTALL_TARGET/log/clients ${NETIP}/${NETMASK}:rw,no_subtree_check,no_root_squash,sync
865        if [ $? -ne 0 ]; then
866                errorAndLog "${FUNCNAME}(): error while adding logging client config"
867                return 1
868        fi
869
870        nfsAddExport $INSTALL_TARGET/tftpboot ${NETIP}/${NETMASK}:ro,no_subtree_check,no_root_squash,sync
871        if [ $? -ne 0 ]; then
872                errorAndLog "${FUNCNAME}(): error while adding second filesystem for the PXE ogclient"
873                return 1
874        fi
875
876        /etc/init.d/nfs-kernel-server restart
877        exportfs -va
878        if [ $? -ne 0 ]; then
879                errorAndLog "${FUNCNAME}(): error while configure exports"
880                return 1
881        fi
882
883        echoAndLog "${FUNCNAME}(): Added NFS configuration to file \"/etc/exports\"."
884        return 0
885}
886
887
888# Añadir entrada en fichero de configuración del servidor NFS.
889# Ejemplos:
890#nfsAddExport /opt/opengnsys 192.168.0.0/255.255.255.0:ro,no_subtree_check,no_root_squash,sync
891#nfsAddExport /opt/opengnsys 192.168.0.0/255.255.255.0
892#nfsAddExport /opt/opengnsys 80.20.2.1:ro 192.123.32.2:rw
893function nfsAddExport()
894{
895        if [ $# -lt 2 ]; then
896                errorAndLog "${FUNCNAME}(): invalid number of parameters"
897                exit 1
898        fi
899        if [ ! -f /etc/exports ]; then
900                errorAndLog "${FUNCNAME}(): /etc/exports don't exists"
901                return 1
902        fi
903
904        local export="$1"
905        local contador=0
906        local cadenaexport
907
908        grep "^$export" /etc/exports > /dev/null
909        if [ $? -eq 0 ]; then
910                echoAndLog "${FUNCNAME}(): $export exists in /etc/exports, omiting"
911                return 0
912        fi
913
914        cadenaexport="${export}"
915        for parametro in $*; do
916                if [ $contador -gt 0 ]; then
917                        host=`echo $parametro | awk -F: '{print $1}'`
918                        options=`echo $parametro | awk -F: '{print $2}'`
919                        if [ "${host}" == "" ]; then
920                                errorAndLog "${FUNCNAME}(): host can't be empty"
921                                return 1
922                        fi
923                        cadenaexport="${cadenaexport}\t${host}"
924
925                        if [ "${options}" != "" ]; then
926                                cadenaexport="${cadenaexport}(${options})"
927                        fi
928                fi
929                let contador=contador+1
930        done
931
932        echo -en "$cadenaexport\n" >> /etc/exports
933
934        echoAndLog "${FUNCNAME}(): add $export to /etc/exports"
935        return 0
936}
937
938
939########################################################################
940## Configuracion servicio Samba
941########################################################################
942
943# Configurar servicios Samba.
944function smbConfigure()
945{
946        echoAndLog "${FUNCNAME}(): Configuring Samba service."
947
948        backupFile $SAMBACFGDIR/smb.conf
949       
950        # Copiar plantailla de recursos para OpenGnSys
951        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
952                $WORKDIR/opengnsys/server/etc/smb-og.conf.tmpl > $SAMBACFGDIR/smb-og.conf
953        # Configurar y recargar Samba"
954        perl -pi -e "s/WORKGROUP/OPENGNSYS/; s/server string \=.*/server string \= OpenGnSys Samba Server/" $SAMBACFGDIR/smb.conf
955        if ! grep -q "smb-og" $SAMBACFGDIR/smb.conf; then
956                echo "include = $SAMBACFGDIR/smb-og.conf" >> $SAMBACFGDIR/smb.conf
957        fi
958        service=$SAMBASERV
959        $ENABLESERVICE; $STARTSERVICE
960        if [ $? -ne 0 ]; then
961                errorAndLog "${FUNCNAME}(): error while configure Samba"
962                return 1
963        fi
964        # Crear clave para usuario de acceso a los recursos.
965        echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | smbpasswd -a -s $OPENGNSYS_CLIENT_USER
966
967        echoAndLog "${FUNCNAME}(): Added Samba configuration."
968        return 0
969}
970
971
972########################################################################
973## Configuracion servicio Rsync
974########################################################################
975
976# Configurar servicio Rsync.
977function rsyncConfigure()
978{
979        echoAndLog "${FUNCNAME}(): Configuring Rsync service."
980
981        backupFile $RSYNCCFGDIR/rsyncd.conf
982
983        # Configurar acceso a Rsync.
984        sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENT_USER/g" \
985                $WORKDIR/opengnsys/repoman/etc/rsyncd.conf.tmpl > $RSYNCCFGDIR/rsyncd.conf
986        sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENT_USER/g" \
987            -e "s/CLIENTPASSWORD/$OPENGNSYS_CLIENT_PASSWD/g" \
988                $WORKDIR/opengnsys/repoman/etc/rsyncd.secrets.tmpl > $RSYNCCFGDIR/rsyncd.secrets
989        chown root.root $RSYNCCFGDIR/rsyncd.secrets
990        chmod 600 $RSYNCCFGDIR/rsyncd.secrets
991
992        # Habilitar Rsync y reiniciar Inetd.
993        if [ -n "$RSYNCSERV" ]; then
994                if [ -f /etc/default/rsync ]; then
995                        perl -pi -e 's/RSYNC_ENABLE=.*/RSYNC_ENABLE=inetd/' /etc/default/rsync
996                fi
997                if [ -f $INETDCFGDIR/rsync ]; then
998                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/rsync
999                else
1000                        cat << EOT > $INETDCFGDIR/rsync
1001service rsync
1002{
1003        disable = no
1004        socket_type = stream
1005        wait = no
1006        user = root
1007        server = $(which rsync)
1008        server_args = --daemon
1009        log_on_failure += USERID
1010        flags = IPv6
1011}
1012EOT
1013                fi
1014                service=$RSYNCSERV $ENABLESERVICE
1015                service=$INETDSERV $STARTSERVICE
1016        fi
1017
1018        echoAndLog "${FUNCNAME}(): Added Rsync configuration."
1019        return 0
1020}
1021
1022       
1023########################################################################
1024## Configuracion servicio DHCP
1025########################################################################
1026
1027# Configurar servicios DHCP.
1028function dhcpConfigure()
1029{
1030        echoAndLog "${FUNCNAME}(): Sample DHCP configuration."
1031
1032        local errcode=0
1033        local i=0
1034        local dev=""
1035
1036        backupFile $DHCPCFGDIR/dhcpd.conf
1037        for dev in ${DEVICE[*]}; do
1038                if [ -n "${SERVERIP[i]}" ]; then
1039                        backupFile $DHCPCFGDIR/dhcpd-$dev.conf
1040                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1041                            -e "s/NETIP/${NETIP[i]}/g" \
1042                            -e "s/NETMASK/${NETMASK[i]}/g" \
1043                            -e "s/NETBROAD/${NETBROAD[i]}/g" \
1044                            -e "s/ROUTERIP/${ROUTERIP[i]}/g" \
1045                            -e "s/DNSIP/$DNSIP/g" \
1046                            $WORKDIR/opengnsys/server/etc/dhcpd.conf.tmpl > $DHCPCFGDIR/dhcpd-$dev.conf || errcode=1
1047                fi
1048                let i++
1049        done
1050        if [ $errcode -ne 0 ]; then
1051                errorAndLog "${FUNCNAME}(): error while configuring DHCP server"
1052                return 1
1053        fi
1054        ln -f $DHCPCFGDIR/dhcpd-$DEFAULTDEV.conf $DHCPCFGDIR/dhcpd.conf
1055        service=$DHCPSERV
1056        $ENABLESERVICE; $STARTSERVICE
1057        echoAndLog "${FUNCNAME}(): Sample DHCP configured in \"$DHCPCFGDIR\"."
1058        return 0
1059}
1060
1061
1062#####################################################################
1063####### Funciones específicas de la instalación de Opengnsys
1064#####################################################################
1065
1066# Copiar ficheros del OpenGnSys Web Console.
1067function installWebFiles()
1068{
1069        local COMPATDIR f
1070
1071        echoAndLog "${FUNCNAME}(): Installing web files..."
1072        # Copiar ficheros.
1073        cp -a $WORKDIR/opengnsys/admin/WebConsole/* $INSTALL_TARGET/www   #*/ comentario para Doxygen.
1074        if [ $? != 0 ]; then
1075                errorAndLog "${FUNCNAME}(): Error copying web files."
1076                exit 1
1077        fi
1078        find $INSTALL_TARGET/www -name .svn -type d -exec rm -fr {} \; 2>/dev/null
1079        # Descomprimir XAJAX.
1080        unzip -o $WORKDIR/opengnsys/admin/xajax_0.5_standard.zip -d $INSTALL_TARGET/www/xajax
1081        # Compatibilidad con dispositivos móviles.
1082        COMPATDIR="$INSTALL_TARGET/www/principal"
1083        for f in acciones administracion aula aulas hardwares imagenes menus repositorios softwares; do
1084                sed 's/clickcontextualnodo/clicksupnodo/g' $COMPATDIR/$f.php > $COMPATDIR/$f.device.php
1085        done
1086        cp -a $COMPATDIR/imagenes.device.php $COMPATDIR/imagenes.device4.php
1087        # Cambiar permisos para ficheros especiales.
1088        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/images/{fotos,iconos}
1089        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/tmp/
1090
1091        echoAndLog "${FUNCNAME}(): Web files installed successfully."
1092}
1093
1094# Configuración específica de Apache.
1095function installWebConsoleApacheConf()
1096{
1097        if [ $# -ne 2 ]; then
1098                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1099                exit 1
1100        fi
1101
1102        local path_opengnsys_base=$1
1103        local path_apache2_confd=$2
1104        local CONSOLEDIR=${path_opengnsys_base}/www
1105
1106        if [ ! -d $path_apache2_confd ]; then
1107                errorAndLog "${FUNCNAME}(): path to apache2 conf.d can not found, verify your server installation"
1108                return 1
1109        fi
1110
1111        mkdir -p $path_apache2_confd/{sites-available,sites-enabled}
1112
1113        echoAndLog "${FUNCNAME}(): creating apache2 config file.."
1114
1115        # Activar HTTPS.
1116        $APACHESSLMOD
1117        $APACHEENABLESSL
1118        $APACHEMAKECERT
1119
1120        # Genera configuración de consola web a partir del fichero plantilla.
1121        sed -e "s/CONSOLEDIR/${CONSOLEDIR//\//\\/}/g" \
1122                $WORKDIR/opengnsys/server/etc/apache.conf.tmpl > $path_opengnsys_base/etc/apache.conf
1123
1124        ln -fs $path_opengnsys_base/etc/apache.conf $path_apache2_confd/$APACHESITESDIR/$APACHEOGSITE
1125        $APACHEENABLEOG
1126        if [ $? -ne 0 ]; then
1127                errorAndLog "${FUNCNAME}(): config file can't be linked to apache conf, verify your server installation"
1128                return 1
1129        else
1130                echoAndLog "${FUNCNAME}(): config file created and linked, restarting apache daemon"
1131                service=$APACHESERV
1132                $ENABLESERVICE; $STARTSERVICE
1133                return 0
1134        fi
1135}
1136
1137
1138# Crear documentación Doxygen para la consola web.
1139function makeDoxygenFiles()
1140{
1141        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
1142        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
1143                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
1144        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
1145                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
1146                return 1
1147        fi
1148        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
1149        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/api
1150        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
1151}
1152
1153
1154# Crea la estructura base de la instalación de opengnsys
1155function createDirs()
1156{
1157        if [ $# -ne 1 ]; then
1158                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1159                exit 1
1160        fi
1161
1162        local path_opengnsys_base="$1"
1163
1164        # Crear estructura de directorios.
1165        echoAndLog "${FUNCNAME}(): creating directory paths in $path_opengnsys_base"
1166        mkdir -p $path_opengnsys_base
1167        mkdir -p $path_opengnsys_base/bin
1168        mkdir -p $path_opengnsys_base/client
1169        mkdir -p $path_opengnsys_base/doc
1170        mkdir -p $path_opengnsys_base/etc
1171        mkdir -p $path_opengnsys_base/lib
1172        mkdir -p $path_opengnsys_base/log/clients
1173        ln -fs $path_opengnsys_base/log /var/log/opengnsys
1174        mkdir -p $path_opengnsys_base/sbin
1175        mkdir -p $path_opengnsys_base/www
1176        mkdir -p $path_opengnsys_base/images
1177        mkdir -p $TFTPCFGDIR
1178        ln -fs $TFTPCFGDIR $path_opengnsys_base/tftpboot
1179        mkdir -p $path_opengnsys_base/tftpboot/pxelinux.cfg
1180        mkdir -p $path_opengnsys_base/tftpboot/menu.lst
1181        if [ $? -ne 0 ]; then
1182                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
1183                return 1
1184        fi
1185
1186        # Crear usuario ficticio.
1187        if id -u $OPENGNSYS_CLIENT_USER &>/dev/null; then
1188                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENT_USER\" is already created"
1189        else
1190                echoAndLog "${FUNCNAME}(): creating OpenGnSys user"
1191                useradd $OPENGNSYS_CLIENT_USER 2>/dev/null
1192                if [ $? -ne 0 ]; then
1193                        errorAndLog "${FUNCNAME}(): error creating OpenGnSys user"
1194                        return 1
1195                fi
1196        fi
1197
1198        # Establecer los permisos básicos.
1199        echoAndLog "${FUNCNAME}(): setting directory permissions"
1200        chmod -R 775 $path_opengnsys_base/{log/clients,images}
1201        chown -R :$OPENGNSYS_CLIENT_USER $path_opengnsys_base/{log/clients,images}
1202        if [ $? -ne 0 ]; then
1203                errorAndLog "${FUNCNAME}(): error while setting permissions"
1204                return 1
1205        fi
1206
1207        # Mover el fichero de registro de instalación al directorio de logs.
1208        echoAndLog "${FUNCNAME}(): moving installation log file"
1209        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
1210        chmod 600 $LOG_FILE
1211
1212        echoAndLog "${FUNCNAME}(): directory paths created"
1213        return 0
1214}
1215
1216# Copia ficheros de configuración y ejecutables genéricos del servidor.
1217function copyServerFiles ()
1218{
1219        if [ $# -ne 1 ]; then
1220                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1221                exit 1
1222        fi
1223
1224        local path_opengnsys_base="$1"
1225
1226        local SOURCES=( server/tftpboot \
1227                        server/bin \
1228                        repoman/bin \
1229                        admin/Sources/Services/ogAdmServerAux
1230                        admin/Sources/Services/ogAdmRepoAux
1231                        installer/opengnsys_uninstall.sh \
1232                        installer/opengnsys_update.sh \
1233                        installer/install_ticket_wolunicast.sh \
1234                        doc )
1235        local TARGETS=( tftpboot \
1236                        bin \
1237                        bin \
1238                        sbin \
1239                        sbin \
1240                        lib \
1241                        lib \
1242                        lib \
1243                        doc )
1244
1245        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
1246                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
1247                exit 1
1248        fi
1249
1250        echoAndLog "${FUNCNAME}(): copying files to server directories"
1251
1252        pushd $WORKDIR/opengnsys
1253        local i
1254        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
1255                if [ -f "${SOURCES[$i]}" ]; then
1256                        echoAndLog "Copying ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1257                        cp -a "${SOURCES[$i]}" "${path_opengnsys_base}/${TARGETS[$i]}"
1258                elif [ -d "${SOURCES[$i]}" ]; then
1259                        echoAndLog "Copying content of ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1260                        cp -a "${SOURCES[$i]}"/* "${path_opengnsys_base}/${TARGETS[$i]}"
1261        else
1262                        echoAndLog "Warning: Unable to copy ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1263                fi
1264        done
1265        popd
1266}
1267
1268####################################################################
1269### Funciones de compilación de código fuente de servicios
1270####################################################################
1271
1272# Compilar los servicios de OpenGnSys
1273function servicesCompilation ()
1274{
1275        local hayErrores=0
1276
1277        # Compilar OpenGnSys Server
1278        echoAndLog "${FUNCNAME}(): Compiling OpenGnSys Admin Server"
1279        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
1280        make && mv ogAdmServer $INSTALL_TARGET/sbin
1281        if [ $? -ne 0 ]; then
1282                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Admin Server"
1283                hayErrores=1
1284        fi
1285        popd
1286        # Compilar OpenGnSys Repository Manager
1287        echoAndLog "${FUNCNAME}(): Compiling OpenGnSys Repository Manager"
1288        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo
1289        make && mv ogAdmRepo $INSTALL_TARGET/sbin
1290        if [ $? -ne 0 ]; then
1291                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Repository Manager"
1292                hayErrores=1
1293        fi
1294        popd
1295        # Compilar OpenGnSys Agent
1296        echoAndLog "${FUNCNAME}(): Compiling OpenGnSys Agent"
1297        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
1298        make && mv ogAdmAgent $INSTALL_TARGET/sbin
1299        if [ $? -ne 0 ]; then
1300                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Agent"
1301                hayErrores=1
1302        fi
1303        popd   
1304        # Compilar OpenGnSys Client
1305        echoAndLog "${FUNCNAME}(): Compiling OpenGnSys Admin Client"
1306        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
1307        make && mv ogAdmClient ../../../../client/shared/bin
1308        if [ $? -ne 0 ]; then
1309                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Admin Client"
1310                hayErrores=1
1311        fi
1312        popd
1313
1314        return $hayErrores
1315}
1316
1317####################################################################
1318### Funciones de copia de la Interface de administración
1319####################################################################
1320
1321# Copiar carpeta de Interface
1322function copyInterfaceAdm ()
1323{
1324        local hayErrores=0
1325       
1326        # Crear carpeta y copiar Interface
1327        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
1328        cp -ar $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client/interfaceAdm
1329        if [ $? -ne 0 ]; then
1330                echoAndLog "${FUNCNAME}(): error while copying Administration Interface Folder"
1331                hayErrores=1
1332        fi
1333        chown $OPENGNSYS_CLIENT_USER:$OPENGNSYS_CLIENT_USER $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
1334        chmod 700 $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
1335
1336        return $hayErrores
1337}
1338
1339####################################################################
1340### Funciones instalacion cliente opengnsys
1341####################################################################
1342
1343function copyClientFiles()
1344{
1345        local errstatus=0
1346
1347        echoAndLog "${FUNCNAME}(): Copying OpenGnSys Client files."
1348        cp -a $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
1349        if [ $? -ne 0 ]; then
1350                errorAndLog "${FUNCNAME}(): error while copying client estructure"
1351                errstatus=1
1352        fi
1353        find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null
1354       
1355        echoAndLog "${FUNCNAME}(): Copying OpenGnSys Cloning Engine files."
1356        mkdir -p $INSTALL_TARGET/client/lib/engine/bin
1357        cp -a $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
1358        if [ $? -ne 0 ]; then
1359                errorAndLog "${FUNCNAME}(): error while copying engine files"
1360                errstatus=1
1361        fi
1362       
1363        if [ $errstatus -eq 0 ]; then
1364                echoAndLog "${FUNCNAME}(): client copy files success."
1365        else
1366                errorAndLog "${FUNCNAME}(): client copy files with errors"
1367        fi
1368
1369        return $errstatus
1370}
1371
1372
1373# Crear cliente OpenGnSys 1.0.2 y posteriores.
1374function clientCreate()
1375{
1376        local DOWNLOADURL="http://$OPENGNSYS_SERVER/downloads"
1377        local FILENAME=ogLive-precise-3.2.0-23-generic-r3257.iso        # 1.0.4-rc2
1378        #local FILENAME=ogLive-raring-3.8.0-22-generic-r3836.iso        # 1.0.5-rc3
1379        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
1380        local TMPDIR=/tmp/${FILENAME%.iso}
1381 
1382        # Descargar cliente, si es necesario.
1383        if [ -s $PROGRAMDIR/$FILENAME ]; then
1384                echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
1385                mv $PROGRAMDIR/$FILENAME $TARGETFILE
1386        else
1387                echoAndLog "${FUNCNAME}(): Loading Client"
1388                wget $DOWNLOADURL/$FILENAME -O $TARGETFILE
1389        fi
1390        if [ ! -s $TARGETFILE ]; then
1391                errorAndLog "${FUNCNAME}(): Error loading OpenGnSys Client"
1392                return 1
1393        fi
1394        # Montar imagen, copiar cliente ogclient y desmontar.
1395        echoAndLog "${FUNCNAME}(): Copying Client files"
1396        mkdir -p $TMPDIR
1397        mount -o loop,ro $TARGETFILE $TMPDIR
1398        cp -av $TMPDIR/ogclient $INSTALL_TARGET/tftpboot
1399        umount $TMPDIR
1400        rmdir $TMPDIR
1401        # Asignar la clave cliente para acceso a Samba.
1402        echoAndLog "${FUNCNAME}(): Set client access key"
1403        echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | \
1404                        $INSTALL_TARGET/bin/setsmbpass
1405
1406        # Establecer los permisos.
1407        find -L $INSTALL_TARGET/tftpboot -type d -exec chmod 755 {} \;
1408        find -L $INSTALL_TARGET/tftpboot -type f -exec chmod 644 {} \;
1409        chown -R :$OPENGNSYS_CLIENT_USER $INSTALL_TARGET/tftpboot/ogclient
1410        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/tftpboot/{menu.lst,pxelinux.cfg}
1411
1412        # Ofrecer md5 del kernel y vmlinuz para ogupdateinitrd en cache
1413        cp -av $INSTALL_TARGET/tftpboot/ogclient/ogvmlinuz* $INSTALL_TARGET/tftpboot
1414        cp -av $INSTALL_TARGET/tftpboot/ogclient/oginitrd.img* $INSTALL_TARGET/tftpboot
1415
1416        echoAndLog "${FUNCNAME}(): Client generation success"
1417}
1418
1419
1420# Configuración básica de servicios de OpenGnSys
1421function openGnsysConfigure()
1422{
1423        local i=0
1424        local dev=""
1425        local CONSOLEURL
1426
1427        echoAndLog "${FUNCNAME}(): Copying init files."
1428        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
1429        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default /etc/default/opengnsys
1430        echoAndLog "${FUNCNAME}(): Creating cron files."
1431        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
1432        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
1433        echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
1434        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
1435
1436        echoAndLog "${FUNCNAME}(): Creating logrotate configuration file."
1437        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1438                $WORKDIR/opengnsys/server/etc/logrotate.tmpl > /etc/logrotate.d/opengnsys
1439
1440        echoAndLog "${FUNCNAME}(): Creating OpenGnSys config files."
1441        for dev in ${DEVICE[*]}; do
1442                if [ -n "${SERVERIP[i]}" ]; then
1443                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1444                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1445                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1446                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1447                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer/ogAdmServer.cfg > $INSTALL_TARGET/etc/ogAdmServer-$dev.cfg
1448                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1449                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo/ogAdmRepo.cfg > $INSTALL_TARGET/etc/ogAdmRepo-$dev.cfg
1450                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1451                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1452                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1453                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1454                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent/ogAdmAgent.cfg > $INSTALL_TARGET/etc/ogAdmAgent-$dev.cfg
1455                        CONSOLEURL="http://${SERVERIP[i]}/opengnsys"
1456                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1457                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1458                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1459                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1460                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
1461                                $INSTALL_TARGET/www/controlacceso.php > $INSTALL_TARGET/www/controlacceso-$dev.php
1462                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1463                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
1464                                $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient/ogAdmClient.cfg > $INSTALL_TARGET/client/etc/ogAdmClient-$dev.cfg
1465                        if [ "$dev" == "$DEFAULTDEV" ]; then
1466                                OPENGNSYS_CONSOLEURL="${CONSOLEURL/http:/https:}"
1467                        fi
1468                fi
1469                let i++
1470        done
1471        ln -f $INSTALL_TARGET/etc/ogAdmServer-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmServer.cfg
1472        ln -f $INSTALL_TARGET/etc/ogAdmRepo-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmRepo.cfg
1473        ln -f $INSTALL_TARGET/etc/ogAdmAgent-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmAgent.cfg
1474        ln -f $INSTALL_TARGET/client/etc/ogAdmClient-$DEFAULTDEV.cfg $INSTALL_TARGET/client/etc/ogAdmClient.cfg
1475        ln -f $INSTALL_TARGET/www/controlacceso-$DEFAULTDEV.php $INSTALL_TARGET/www/controlacceso.php
1476        chown root:root $INSTALL_TARGET/etc/{ogAdmServer,ogAdmAgent}*.cfg
1477        chmod 600 $INSTALL_TARGET/etc/{ogAdmServer,ogAdmAgent}*.cfg
1478        chown $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/controlacceso*.php
1479        chmod 600 $INSTALL_TARGET/www/controlacceso*.php
1480        echoAndLog "${FUNCNAME}(): Starting OpenGnSys services."
1481        service="opengnsys"
1482        $ENABLESERVICE; $STARTSERVICE
1483}
1484
1485
1486#####################################################################
1487#######  Función de resumen informativo de la instalación
1488#####################################################################
1489
1490function installationSummary()
1491{
1492        # Crear fichero de versión y revisión, si no existe.
1493        local VERSIONFILE="$INSTALL_TARGET/doc/VERSION.txt"
1494        local REVISION=$(LANG=C svn info $SVN_URL|awk '/Rev:/ {print "r"$4}')
1495        [ -f $VERSIONFILE ] || echo "OpenGnSys" >$VERSIONFILE
1496        perl -pi -e "s/($| r[0-9]*)/ $REVISION/" $VERSIONFILE
1497
1498        # Mostrar información.
1499        echo
1500        echoAndLog "OpenGnSys Installation Summary"
1501        echo       "=============================="
1502        echoAndLog "Project version:                  $(cat $VERSIONFILE 2>/dev/null)"
1503        echoAndLog "Installation directory:           $INSTALL_TARGET"
1504        echoAndLog "Installation log file:            $LOG_FILE"
1505        echoAndLog "Repository directory:             $INSTALL_TARGET/images"
1506        echoAndLog "DHCP configuration directory:     $DHCPCFGDIR"
1507        echoAndLog "TFTP configuration directory:     $TFTPCFGDIR"
1508        echoAndLog "Samba configuration directory:    $SAMBACFGDIR"
1509        echoAndLog "Web Console URL:                  $OPENGNSYS_CONSOLEURL"
1510        echoAndLog "Web Console access data:          specified in installer script"
1511        echo
1512        echoAndLog "Post-Installation Instructions:"
1513        echo       "==============================="
1514        echoAndLog "Change IPTables and SELinux system configuration, if needed."
1515        echoAndLog "Review or edit all configuration files."
1516        echoAndLog "Insert DHCP configuration data and restart service."
1517        echoAndLog "Optional: Log-in as Web Console admin user."
1518        echoAndLog " - Review default Organization data and assign access to users."
1519        echoAndLog "Log-in as Web Console organization user."
1520        echoAndLog " - Insert OpenGnSys data (labs, computers, menus, etc)."
1521echo
1522}
1523
1524
1525
1526#####################################################################
1527####### Proceso de instalación de OpenGnSys
1528#####################################################################
1529
1530echoAndLog "OpenGnSys installation begins at $(date)"
1531pushd $WORKDIR
1532
1533# Detectar datos iniciales de auto-configuración del instalador.
1534autoConfigure
1535
1536# Detectar parámetros de red y comprobar si hay conexión.
1537getNetworkSettings
1538if [ $? -ne 0 ]; then
1539        errorAndLog "Error reading default network settings."
1540        exit 1
1541fi
1542checkNetworkConnection
1543if [ $? -ne 0 ]; then
1544        errorAndLog "Error connecting to server. Causes:"
1545        errorAndLog " - Network is unreachable, review devices parameters."
1546        errorAndLog " - You are inside a private network, configure the proxy service."
1547        errorAndLog " - Server is temporally down, try agian later."
1548        exit 1
1549fi
1550
1551# Detener servicios de OpenGnSys, si están activos previamente.
1552[ -f /etc/init.d/opengnsys ] && /etc/init.d/opengnsys stop
1553
1554# Actualizar repositorios
1555updatePackageList
1556
1557# Instalación de dependencias (paquetes de sistema operativo).
1558declare -a notinstalled
1559checkDependencies DEPENDENCIES notinstalled
1560if [ $? -ne 0 ]; then
1561        installDependencies notinstalled
1562        if [ $? -ne 0 ]; then
1563                echoAndLog "Error while installing some dependeces, please verify your server installation before continue"
1564                exit 1
1565        fi
1566fi
1567if [ -n "$INSTALLEXTRADEPS" ]; then
1568        echoAndLog "Installing extra dependencies"
1569        for (( i=0; i<${#INSTALLEXTRADEPS[*]}; i++ )); do
1570                eval ${INSTALLEXTRADEPS[i]}
1571        done
1572fi     
1573
1574# Detectar datos de auto-configuración después de instalar paquetes.
1575autoConfigurePost
1576
1577# Arbol de directorios de OpenGnSys.
1578createDirs ${INSTALL_TARGET}
1579if [ $? -ne 0 ]; then
1580        errorAndLog "Error while creating directory paths!"
1581        exit 1
1582fi
1583
1584# Si es necesario, descarga el repositorio de código en directorio temporal
1585if [ $USESVN -eq 1 ]; then
1586        svnExportCode $SVN_URL
1587        if [ $? -ne 0 ]; then
1588                errorAndLog "Error while getting code from svn"
1589                exit 1
1590        fi
1591else
1592        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
1593fi
1594
1595# Compilar código fuente de los servicios de OpenGnSys.
1596servicesCompilation
1597if [ $? -ne 0 ]; then
1598        errorAndLog "Error while compiling OpenGnsys services"
1599        exit 1
1600fi
1601
1602# Copiar carpeta Interface entre administración y motor de clonación.
1603copyInterfaceAdm
1604if [ $? -ne 0 ]; then
1605        errorAndLog "Error while copying Administration Interface"
1606        exit 1
1607fi
1608
1609# Configuración de TFTP.
1610tftpConfigure
1611
1612# Configuración de Samba.
1613smbConfigure
1614if [ $? -ne 0 ]; then
1615        errorAndLog "Error while configuring Samba server!"
1616        exit 1
1617fi
1618
1619# Configuración de Rsync.
1620rsyncConfigure
1621
1622# Configuración ejemplo DHCP.
1623dhcpConfigure
1624if [ $? -ne 0 ]; then
1625        errorAndLog "Error while copying your dhcp server files!"
1626        exit 1
1627fi
1628
1629# Copiar ficheros de servicios OpenGnSys Server.
1630copyServerFiles ${INSTALL_TARGET}
1631if [ $? -ne 0 ]; then
1632        errorAndLog "Error while copying the server files!"
1633        exit 1
1634fi
1635
1636# Instalar Base de datos de OpenGnSys Admin.
1637isInArray notinstalled "mysql-server"
1638if [ $? -eq 0 ]; then
1639        service=$MYSQLSERV
1640        $ENABLESERVICE; $STARTSERVICE
1641        mysqlSetRootPassword "${MYSQL_ROOT_PASSWORD}"
1642else
1643        mysqlGetRootPassword
1644fi
1645
1646mysqlTestConnection "${MYSQL_ROOT_PASSWORD}"
1647if [ $? -ne 0 ]; then
1648        errorAndLog "Error while connection to mysql"
1649        exit 1
1650fi
1651mysqlDbExists ${OPENGNSYS_DATABASE}
1652if [ $? -ne 0 ]; then
1653        echoAndLog "Creating Web Console database"
1654        mysqlCreateDb ${OPENGNSYS_DATABASE}
1655        if [ $? -ne 0 ]; then
1656                errorAndLog "Error while creating Web Console database"
1657                exit 1
1658        fi
1659else
1660        echoAndLog "Web Console database exists, ommiting creation"
1661fi
1662
1663mysqlCheckUserExists ${OPENGNSYS_DB_USER}
1664if [ $? -ne 0 ]; then
1665        echoAndLog "Creating user in database"
1666        mysqlCreateAdminUserToDb ${OPENGNSYS_DATABASE} ${OPENGNSYS_DB_USER} "${OPENGNSYS_DB_PASSWD}"
1667        if [ $? -ne 0 ]; then
1668                errorAndLog "Error while creating database user"
1669                exit 1
1670        fi
1671
1672fi
1673
1674mysqlCheckDbIsEmpty ${OPENGNSYS_DATABASE}
1675if [ $? -eq 0 ]; then
1676        echoAndLog "Creating tables..."
1677        if [ -f $WORKDIR/$OPENGNSYS_DB_CREATION_FILE ]; then
1678                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_CREATION_FILE
1679        else
1680                errorAndLog "Unable to locate $WORKDIR/$OPENGNSYS_DB_CREATION_FILE!!"
1681                exit 1
1682        fi
1683else
1684        # Si existe fichero ogBDAdmin-VersLocal-VersRepo.sql; aplicar cambios.
1685        INSTVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt)
1686        REPOVERSION=$(awk '{print $2}' $WORKDIR/opengnsys/doc/VERSION.txt)
1687        OPENGNSYS_DB_UPDATE_FILE="opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
1688        if [ -f $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE ]; then
1689                echoAndLog "Updating tables from version $INSTVERSION to $REPOVERSION"
1690                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE
1691        else
1692                echoAndLog "Database unchanged."
1693        fi
1694fi
1695# Eliminar fichero temporal con credenciales de acceso a MySQL.
1696rm -f $TMPMYCNF
1697
1698# copiando paqinas web
1699installWebFiles
1700# Generar páqinas web de documentación de la API
1701makeDoxygenFiles
1702
1703# creando configuracion de apache2
1704installWebConsoleApacheConf $INSTALL_TARGET $APACHECFGDIR
1705if [ $? -ne 0 ]; then
1706        errorAndLog "Error configuring Apache for OpenGnSys Admin"
1707        exit 1
1708fi
1709
1710popd
1711
1712# Crear la estructura de los accesos al servidor desde el cliente (shared)
1713copyClientFiles
1714if [ $? -ne 0 ]; then
1715        errorAndLog "Error creating client structure"
1716fi
1717
1718# Crear la estructura del cliente de OpenGnSys
1719clientCreate
1720if [ $? -ne 0 ]; then
1721        errorAndLog "Error creating client"
1722        exit 1
1723fi
1724
1725# Configuración de servicios de OpenGnSys
1726openGnsysConfigure
1727
1728# Mostrar sumario de la instalación e instrucciones de post-instalación.
1729installationSummary
1730
1731#rm -rf $WORKDIR
1732echoAndLog "OpenGnSys installation finished at $(date)"
1733exit 0
1734
Note: See TracBrowser for help on using the repository browser.