source: installer/opengnsys_installer.sh @ 0edd937

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 0edd937 was 1f7b2d0, checked in by ramon <ramongomez@…>, 11 years ago

#648: Instalador ejecuta al final el script checkperms para asignar correctamente permisos de ficheros y directorios.

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

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