source: installer/opengnsys_installer.sh @ 0703783

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 0703783 was e5f9c147, checked in by irina <irinagomez@…>, 11 years ago

opengnsys_installer.sh: correncion errata funcion autoConfigurePost

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

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