source: installer/opengnsys_installer.sh @ a012113

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 a012113 was 0a735488, checked in by ramon <ramongomez@…>, 10 years ago

#673: Añadir nuevos tickets resueltos y los ampliar comentarios del instalador.

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

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