source: installer/opengnsys_installer.sh @ 6dedc02

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 6dedc02 was 7829e4e, checked in by ramon <ramongomez@…>, 10 years ago

#708: Integrar código del ticket:708 en versión 1.1.

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

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