source: installer/opengnsys_installer.sh @ c7ade22

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 c7ade22 was c7ade22, checked in by ramon <ramongomez@…>, 8 years ago

#730: Evitar que quede deshabilitado el inicio de MySQL en Ubuntu 16.04 (que sustituye Upstart por SystemD).

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

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