source: installer/opengnsys_installer.sh @ 030ee20

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

#730: Evitar errores en algunas clásulas GROUP BY cuando MySQL tiene habilitado el modo ONLY_FULL_GROUP_BY (por deecto en MySQL 5.7 de Ubuntu 16.04).

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

  • Property mode set to 100755
File size: 57.3 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        # Quitar modo ONLY_FULL_GROUP_BY de MySQL (ticket #730).
712        mysql --defaults-extra-file=$TMPMYCNF -e "SET GLOBAL sql_mode=(SELECT TRIM(BOTH ',' FROM REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')));"
713
714        echoAndLog "${FUNCNAME}(): database $database created"
715        return 0
716}
717
718# Comprueba si ya está definido el usuario de acceso a la BD.
719function mysqlCheckUserExists()
720{
721        if [ $# -ne 1 ]; then
722                errorAndLog "${FUNCNAME}(): invalid number of parameters"
723                exit 1
724        fi
725
726        local userdb="$1"
727
728        echoAndLog "${FUNCNAME}(): checking if $userdb exists..."
729        echo "select user from user where user='${userdb}'\\G" |mysql --defaults-extra-file=$TMPMYCNF mysql | grep user
730        if [ $? -ne 0 ]; then
731                echoAndLog "${FUNCNAME}(): user doesn't exists"
732                return 1
733        else
734                echoAndLog "${FUNCNAME}(): user already exists"
735                return 0
736        fi
737
738}
739
740# Crea un usuario administrativo para la base de datos
741function mysqlCreateAdminUserToDb()
742{
743        if [ $# -ne 3 ]; then
744                errorAndLog "${FUNCNAME}(): invalid number of parameters"
745                exit 1
746        fi
747
748        local database="$1"
749        local userdb="$2"
750        local passdb="$3"
751
752        echoAndLog "${FUNCNAME}(): creating admin user ${userdb} to database ${database}"
753
754        cat > $WORKDIR/create_${database}.sql <<EOF
755GRANT USAGE ON *.* TO '${userdb}'@'localhost' IDENTIFIED BY '${passdb}' ;
756GRANT ALL PRIVILEGES ON ${database}.* TO '${userdb}'@'localhost' WITH GRANT OPTION ;
757FLUSH PRIVILEGES ;
758EOF
759        mysql --defaults-extra-file=$TMPMYCNF < $WORKDIR/create_${database}.sql
760        if [ $? -ne 0 ]; then
761                errorAndLog "${FUNCNAME}(): error while creating user in mysql"
762                rm -f $WORKDIR/create_${database}.sql
763                return 1
764        else
765                echoAndLog "${FUNCNAME}(): user created ok"
766                rm -f $WORKDIR/create_${database}.sql
767                return 0
768        fi
769}
770
771
772#####################################################################
773####### Funciones para el manejo de Subversion
774#####################################################################
775
776# Obtiene el código fuente del proyecto desde el servidor SVN.
777function svnExportCode()
778{
779        if [ $# -ne 1 ]; then
780                errorAndLog "${FUNCNAME}(): invalid number of parameters"
781                exit 1
782        fi
783
784        local url="$1"
785
786        echoAndLog "${FUNCNAME}(): downloading subversion code..."
787
788        svn export --force "$url" opengnsys
789        if [ $? -ne 0 ]; then
790                errorAndLog "${FUNCNAME}(): error getting OpenGnsys code from $url"
791                return 1
792        fi
793        echoAndLog "${FUNCNAME}(): subversion code downloaded"
794        return 0
795}
796
797
798############################################################
799###  Detectar red
800############################################################
801
802# Comprobar si existe conexión.
803function checkNetworkConnection()
804{
805        echoAndLog "${FUNCNAME}(): Disabling Firewall: $FIREWALLSERV."
806        if [ -n "$FIREWALLSERV" ]; then
807                service=$FIREWALLSERV
808                $STOPSERVICE; $DISABLESERVICE
809        fi
810
811        echoAndLog "${FUNCNAME}(): Checking OpenGnsys server conectivity."
812        OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"www.opengnsys.es"}
813        if which wget &>/dev/null; then
814                wget --spider -q $OPENGNSYS_SERVER
815        elif which curl &>/dev/null; then
816                curl --connect-timeout 10 -s $OPENGNSYS_SERVER -o /dev/null
817        else
818                echoAndLog "${FUNCNAME}(): Cannot execute \"wget\" nor \"curl\"."
819                return 1
820        fi
821}
822
823# Obtener los parámetros de red de la interfaz por defecto.
824function getNetworkSettings()
825{
826        # Arrays globales definidas:
827        # - DEVICE:     nombres de dispositivos de red activos.
828        # - SERVERIP:   IPs locales del servidor.
829        # - NETIP:      IPs de redes.
830        # - NETMASK:    máscaras de red.
831        # - NETBROAD:   IPs de difusión de redes.
832        # - ROUTERIP:   IPs de routers.
833        # Otras variables globales:
834        # - DEFAULTDEV: dispositivo de red por defecto.
835        # - DNSIP:      IP del servidor DNS principal.
836
837        local i=0
838        local dev=""
839
840        echoAndLog "${FUNCNAME}(): Detecting network parameters."
841        DEVICE=( $(ip -o link show up | awk '!/loopback/ {sub(/:.*/,"",$2); print $2}') )
842        if [ -z "$DEVICE" ]; then
843                errorAndLog "${FUNCNAME}(): Network devices not detected."
844                exit 1
845        fi
846        for dev in ${DEVICE[*]}; do
847                SERVERIP[i]=$(ip -o addr show dev $dev | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4)}')
848                if [ -n "${SERVERIP[i]}" ]; then
849                        NETMASK[i]=$(LANG=C ifconfig $dev | \
850                                                awk '/Mask/ {sub(/.*:/,"",$4); print $4}
851                                                     /netmask/ {print $4}')
852                        NETBROAD[i]=$(ip -o addr show dev $dev | awk '$3~/inet$/ {print ($6)}')
853                        NETIP[i]=$(ip route | awk -v d="$dev" '$3==d && /src/ {sub (/\/.*/,""); print $1}')
854                        ROUTERIP[i]=$(ip route | awk -v d="$dev" '$1=="default" && $5==d {print $3}')
855                        DEFAULTDEV=${DEFAULTDEV:-"$dev"}
856                fi
857                let i++
858        done
859        DNSIP=$(awk '/nameserver/ {print $2}' /etc/resolv.conf | head -n1)
860        if [ -z "${NETIP[*]}" -o -z "${NETMASK[*]}" ]; then
861                errorAndLog "${FUNCNAME}(): Network not detected."
862                exit 1
863        fi
864
865        # Variables de ejecución de Apache
866        # - APACHE_RUN_USER
867        # - APACHE_RUN_GROUP
868        if [ -f $APACHECFGDIR/envvars ]; then
869                source $APACHECFGDIR/envvars
870        fi
871        APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
872        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
873
874        echoAndLog "${FUNCNAME}(): Default network device: $DEFAULTDEV."
875}
876
877
878############################################################
879### Esqueleto para el Servicio pxe y contenedor tftpboot ###
880############################################################
881
882function tftpConfigure()
883{
884        echoAndLog "${FUNCNAME}(): Configuring TFTP service."
885        # Habilitar TFTP y reiniciar Inetd.
886        if [ -n "$TFTPSERV" ]; then
887                if [ -f $INETDCFGDIR/$TFTPSERV ]; then
888                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/$TFTPSERV
889                else
890                        service=$TFTPSERV
891                        $ENABLESERVICE; $STARTSERVICE
892                fi
893        fi
894        service=$INETDSERV
895        $ENABLESERVICE; $STARTSERVICE
896
897        # Copiar ficheros de Syslinux.
898        cp -a $SYSLINUXDIR $TFTPCFGDIR/syslinux
899
900        # comprobamos el servicio tftp
901        sleep 1
902        testPxe
903}
904
905# Comprueba que haya conexión al servicio TFTP/PXE.
906function testPxe ()
907{
908        echoAndLog "${FUNCNAME}(): Checking TFTP service... please wait."
909        echo "test" >$TFTPCFGDIR/testpxe
910        tftp -v 127.0.0.1 -c get testpxe /tmp/testpxe && echoAndLog "TFTP service is OK." || errorAndLog "TFTP service is down."
911        rm -f $TFTPCFGDIR/testpxe /tmp/testpxe
912}
913
914
915########################################################################
916## Configuración servicio Samba
917########################################################################
918
919# Configurar servicios Samba.
920function smbConfigure()
921{
922        echoAndLog "${FUNCNAME}(): Configuring Samba service."
923
924        backupFile $SAMBACFGDIR/smb.conf
925       
926        # Copiar plantailla de recursos para OpenGnsys
927        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
928                $WORKDIR/opengnsys/server/etc/smb-og.conf.tmpl > $SAMBACFGDIR/smb-og.conf
929        # Configurar y recargar Samba"
930        perl -pi -e "s/WORKGROUP/OPENGNSYS/; s/server string \=.*/server string \= OpenGnsys Samba Server/" $SAMBACFGDIR/smb.conf
931        if ! grep -q "smb-og" $SAMBACFGDIR/smb.conf; then
932                echo "include = $SAMBACFGDIR/smb-og.conf" >> $SAMBACFGDIR/smb.conf
933        fi
934        service=$SAMBASERV
935        $ENABLESERVICE; $STARTSERVICE
936        if [ $? -ne 0 ]; then
937                errorAndLog "${FUNCNAME}(): error while configure Samba"
938                return 1
939        fi
940        # Crear clave para usuario de acceso a los recursos.
941        echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | smbpasswd -a -s $OPENGNSYS_CLIENT_USER
942
943        echoAndLog "${FUNCNAME}(): Added Samba configuration."
944        return 0
945}
946
947
948########################################################################
949## Configuración servicio Rsync
950########################################################################
951
952# Configurar servicio Rsync.
953function rsyncConfigure()
954{
955        echoAndLog "${FUNCNAME}(): Configuring Rsync service."
956
957        backupFile $RSYNCCFGDIR/rsyncd.conf
958
959        # Configurar acceso a Rsync.
960        sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENT_USER/g" \
961                $WORKDIR/opengnsys/repoman/etc/rsyncd.conf.tmpl > $RSYNCCFGDIR/rsyncd.conf
962        sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENT_USER/g" \
963            -e "s/CLIENTPASSWORD/$OPENGNSYS_CLIENT_PASSWD/g" \
964                $WORKDIR/opengnsys/repoman/etc/rsyncd.secrets.tmpl > $RSYNCCFGDIR/rsyncd.secrets
965        chown root.root $RSYNCCFGDIR/rsyncd.secrets
966        chmod 600 $RSYNCCFGDIR/rsyncd.secrets
967
968        # Habilitar Rsync y reiniciar Inetd.
969        if [ -n "$RSYNCSERV" ]; then
970                if [ -f /etc/default/rsync ]; then
971                        perl -pi -e 's/RSYNC_ENABLE=.*/RSYNC_ENABLE=inetd/' /etc/default/rsync
972                fi
973                if [ -f $INETDCFGDIR/rsync ]; then
974                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/rsync
975                else
976                        cat << EOT > $INETDCFGDIR/rsync
977service rsync
978{
979        disable = no
980        socket_type = stream
981        wait = no
982        user = root
983        server = $(which rsync)
984        server_args = --daemon
985        log_on_failure += USERID
986        flags = IPv6
987}
988EOT
989                fi
990                service=$RSYNCSERV $ENABLESERVICE
991                service=$INETDSERV $STARTSERVICE
992        fi
993
994        echoAndLog "${FUNCNAME}(): Added Rsync configuration."
995        return 0
996}
997
998       
999########################################################################
1000## Configuración servicio DHCP
1001########################################################################
1002
1003# Configurar servicios DHCP.
1004function dhcpConfigure()
1005{
1006        echoAndLog "${FUNCNAME}(): Sample DHCP configuration."
1007
1008        local errcode=0
1009        local i=0
1010        local dev=""
1011
1012        backupFile $DHCPCFGDIR/dhcpd.conf
1013        for dev in ${DEVICE[*]}; do
1014                if [ -n "${SERVERIP[i]}" ]; then
1015                        backupFile $DHCPCFGDIR/dhcpd-$dev.conf
1016                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1017                            -e "s/NETIP/${NETIP[i]}/g" \
1018                            -e "s/NETMASK/${NETMASK[i]}/g" \
1019                            -e "s/NETBROAD/${NETBROAD[i]}/g" \
1020                            -e "s/ROUTERIP/${ROUTERIP[i]}/g" \
1021                            -e "s/DNSIP/$DNSIP/g" \
1022                            $WORKDIR/opengnsys/server/etc/dhcpd.conf.tmpl > $DHCPCFGDIR/dhcpd-$dev.conf || errcode=1
1023                fi
1024                let i++
1025        done
1026        if [ $errcode -ne 0 ]; then
1027                errorAndLog "${FUNCNAME}(): error while configuring DHCP server"
1028                return 1
1029        fi
1030        ln -f $DHCPCFGDIR/dhcpd-$DEFAULTDEV.conf $DHCPCFGDIR/dhcpd.conf
1031        service=$DHCPSERV
1032        $ENABLESERVICE; $STARTSERVICE
1033        echoAndLog "${FUNCNAME}(): Sample DHCP configured in \"$DHCPCFGDIR\"."
1034        return 0
1035}
1036
1037
1038#####################################################################
1039####### Funciones específicas de la instalación de Opengnsys
1040#####################################################################
1041
1042# Copiar ficheros del OpenGnsys Web Console.
1043function installWebFiles()
1044{
1045        local COMPATDIR f
1046        local XAJAXFILE="xajax_0.5_standard.zip"
1047        local SLIMFILE="slim-2.6.1.zip"
1048        local SWAGGERFILE="swagger-ui-2.2.5.zip"
1049
1050        echoAndLog "${FUNCNAME}(): Installing web files..."
1051        # Copiar ficheros.
1052        cp -a $WORKDIR/opengnsys/admin/WebConsole/* $INSTALL_TARGET/www   #*/ comentario para Doxygen.
1053        if [ $? != 0 ]; then
1054                errorAndLog "${FUNCNAME}(): Error copying web files."
1055                exit 1
1056        fi
1057        find $INSTALL_TARGET/www -name .svn -type d -exec rm -fr {} \; 2>/dev/null
1058
1059        # Descomprimir librerías: XAJAX, Slim y Swagger-UI.
1060        unzip -o $WORKDIR/opengnsys/admin/$XAJAXFILE -d $INSTALL_TARGET/www/xajax
1061        unzip -o $WORKDIR/opengnsys/admin/$SLIMFILE -d $INSTALL_TARGET/www/rest
1062        unzip -o $WORKDIR/opengnsys/admin/$SWAGGERFILE -d $INSTALL_TARGET/www/rest
1063
1064        # Compatibilidad con dispositivos móviles.
1065        COMPATDIR="$INSTALL_TARGET/www/principal"
1066        for f in acciones administracion aula aulas hardwares imagenes menus repositorios softwares; do
1067                sed 's/clickcontextualnodo/clicksupnodo/g' $COMPATDIR/$f.php > $COMPATDIR/$f.device.php
1068        done
1069        cp -a $COMPATDIR/imagenes.device.php $COMPATDIR/imagenes.device4.php
1070        # Cambiar permisos para ficheros especiales.
1071        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/images/{fotos,iconos}
1072        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/tmp/
1073        # Fichero de logs del agente OGAgent.
1074        touch $INSTALL_TARGET/log/ogagent.log
1075        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/log/ogagent.log
1076
1077        echoAndLog "${FUNCNAME}(): Web files installed successfully."
1078}
1079
1080# Copiar ficheros en la zona de descargas de OpenGnsys Web Console.
1081function installDownloadableFiles()
1082{
1083        local FILENAME=ogagentpkgs-$INSTVERSION.tar.gz
1084        local TARGETFILE=$WORKDIR/$FILENAME
1085 
1086        # Descargar archivo comprimido, si es necesario.
1087        if [ -s $PROGRAMDIR/$FILENAME ]; then
1088                echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
1089                mv $PROGRAMDIR/$FILENAME $TARGETFILE
1090        else
1091                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
1092                wget $DOWNLOADURL/$FILENAME -O $TARGETFILE
1093        fi
1094        if [ ! -s $TARGETFILE ]; then
1095                errorAndLog "${FUNCNAME}(): Cannot download $FILENAME"
1096                return 1
1097        fi
1098       
1099        # Descomprimir fichero en zona de descargas.
1100        tar xvzf $TARGETFILE -C $INSTALL_TARGET/www/descargas
1101        if [ $? != 0 ]; then
1102                errorAndLog "${FUNCNAME}(): Error uncompressing archive."
1103                exit 1
1104        fi
1105}
1106
1107# Configuración específica de Apache.
1108function installWebConsoleApacheConf()
1109{
1110        if [ $# -ne 2 ]; then
1111                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1112                exit 1
1113        fi
1114
1115        local path_opengnsys_base="$1"
1116        local path_apache2_confd="$2"
1117        local CONSOLEDIR=${path_opengnsys_base}/www
1118
1119        if [ ! -d $path_apache2_confd ]; then
1120                errorAndLog "${FUNCNAME}(): path to apache2 conf.d can not found, verify your server installation"
1121                return 1
1122        fi
1123
1124        mkdir -p $path_apache2_confd/{sites-available,sites-enabled}
1125
1126        echoAndLog "${FUNCNAME}(): creating apache2 config file.."
1127
1128        # Activar HTTPS.
1129        $APACHESSLMOD
1130        $APACHEENABLESSL
1131        $APACHEMAKECERT
1132        # Activar módulo Rewrite.
1133        $APACHEREWRITEMOD
1134        # Genera configuración de consola web a partir del fichero plantilla.
1135        if [ -n "$(apachectl -v | grep "2\.[0-2]")" ]; then
1136                # Configuración para versiones anteriores de Apache.
1137                sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
1138                        $WORKDIR/opengnsys/server/etc/apache-prev2.4.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}
1139        else
1140                # Configuración específica a partir de Apache 2.4
1141                sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
1142                        $WORKDIR/opengnsys/server/etc/apache.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf
1143        fi
1144        $APACHEENABLEOG
1145        if [ $? -ne 0 ]; then
1146                errorAndLog "${FUNCNAME}(): config file can't be linked to apache conf, verify your server installation"
1147                return 1
1148        fi
1149        echoAndLog "${FUNCNAME}(): config file created and linked, restarting apache daemon"
1150        service=$APACHESERV
1151        $ENABLESERVICE; $STARTSERVICE
1152        return 0
1153}
1154
1155
1156# Crear documentación Doxygen para la consola web.
1157function makeDoxygenFiles()
1158{
1159        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
1160        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
1161                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
1162        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
1163                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
1164                return 1
1165        fi
1166        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
1167        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/api
1168        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
1169}
1170
1171
1172# Crea la estructura base de la instalación de opengnsys
1173function createDirs()
1174{
1175        if [ $# -ne 1 ]; then
1176                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1177                exit 1
1178        fi
1179
1180        local path_opengnsys_base="$1"
1181
1182        # Crear estructura de directorios.
1183        echoAndLog "${FUNCNAME}(): creating directory paths in $path_opengnsys_base"
1184        mkdir -p $path_opengnsys_base
1185        mkdir -p $path_opengnsys_base/bin
1186        mkdir -p $path_opengnsys_base/client
1187        mkdir -p $path_opengnsys_base/doc
1188        mkdir -p $path_opengnsys_base/etc
1189        mkdir -p $path_opengnsys_base/lib
1190        mkdir -p $path_opengnsys_base/log/clients
1191        ln -fs $path_opengnsys_base/log /var/log/opengnsys
1192        mkdir -p $path_opengnsys_base/sbin
1193        mkdir -p $path_opengnsys_base/www
1194        mkdir -p $path_opengnsys_base/images/group
1195        mkdir -p $TFTPCFGDIR
1196        ln -fs $TFTPCFGDIR $path_opengnsys_base/tftpboot
1197        mkdir -p $path_opengnsys_base/tftpboot/menu.lst
1198        if [ $? -ne 0 ]; then
1199                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
1200                return 1
1201        fi
1202
1203        # Crear usuario ficticio.
1204        if id -u $OPENGNSYS_CLIENT_USER &>/dev/null; then
1205                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENT_USER\" is already created"
1206        else
1207                echoAndLog "${FUNCNAME}(): creating OpenGnsys user"
1208                useradd $OPENGNSYS_CLIENT_USER 2>/dev/null
1209                if [ $? -ne 0 ]; then
1210                        errorAndLog "${FUNCNAME}(): error creating OpenGnsys user"
1211                        return 1
1212                fi
1213        fi
1214
1215        # Establecer los permisos básicos.
1216        echoAndLog "${FUNCNAME}(): setting directory permissions"
1217        chmod -R 775 $path_opengnsys_base/{log/clients,images}
1218        chown -R :$OPENGNSYS_CLIENT_USER $path_opengnsys_base/{log/clients,images}
1219        if [ $? -ne 0 ]; then
1220                errorAndLog "${FUNCNAME}(): error while setting permissions"
1221                return 1
1222        fi
1223
1224        # Mover el fichero de registro de instalación al directorio de logs.
1225        echoAndLog "${FUNCNAME}(): moving installation log file"
1226        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
1227        chmod 600 $LOG_FILE
1228
1229        echoAndLog "${FUNCNAME}(): directory paths created"
1230        return 0
1231}
1232
1233# Copia ficheros de configuración y ejecutables genéricos del servidor.
1234function copyServerFiles ()
1235{
1236        if [ $# -ne 1 ]; then
1237                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1238                exit 1
1239        fi
1240
1241        local path_opengnsys_base="$1"
1242
1243        # Lista de ficheros y directorios origen y de directorios destino.
1244        local SOURCES=( server/tftpboot \
1245                        server/bin \
1246                        repoman/bin \
1247                        server/lib \
1248                        admin/Sources/Services/ogAdmServerAux
1249                        admin/Sources/Services/ogAdmRepoAux
1250                        installer/opengnsys_uninstall.sh \
1251                        installer/opengnsys_update.sh \
1252                        installer/opengnsys_export.sh \
1253                        installer/opengnsys_import.sh \
1254                        doc )
1255        local TARGETS=( tftpboot \
1256                        bin \
1257                        bin \
1258                        lib \
1259                        sbin \
1260                        sbin \
1261                        lib \
1262                        lib \
1263                        lib \
1264                        lib \
1265                        doc )
1266
1267        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
1268                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
1269                exit 1
1270        fi
1271
1272        # Copiar ficheros.
1273        echoAndLog "${FUNCNAME}(): copying files to server directories"
1274
1275        pushd $WORKDIR/opengnsys
1276        local i
1277        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
1278                if [ -f "${SOURCES[$i]}" ]; then
1279                        echoAndLog "Copying ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1280                        cp -a "${SOURCES[$i]}" "${path_opengnsys_base}/${TARGETS[$i]}"
1281                elif [ -d "${SOURCES[$i]}" ]; then
1282                        echoAndLog "Copying content of ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1283                        cp -a "${SOURCES[$i]}"/* "${path_opengnsys_base}/${TARGETS[$i]}"
1284        else
1285                        warningAndLog "Unable to copy ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1286                fi
1287        done
1288
1289        popd
1290}
1291
1292####################################################################
1293### Funciones de compilación de código fuente de servicios
1294####################################################################
1295
1296# Compilar los servicios de OpenGnsys
1297function servicesCompilation ()
1298{
1299        local hayErrores=0
1300
1301        # Compilar OpenGnsys Server
1302        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Server"
1303        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
1304        make && mv ogAdmServer $INSTALL_TARGET/sbin
1305        if [ $? -ne 0 ]; then
1306                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Server"
1307                hayErrores=1
1308        fi
1309        popd
1310        # Compilar OpenGnsys Repository Manager
1311        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Repository Manager"
1312        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo
1313        make && mv ogAdmRepo $INSTALL_TARGET/sbin
1314        if [ $? -ne 0 ]; then
1315                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Repository Manager"
1316                hayErrores=1
1317        fi
1318        popd
1319        # Compilar OpenGnsys Agent
1320        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Agent"
1321        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
1322        make && mv ogAdmAgent $INSTALL_TARGET/sbin
1323        if [ $? -ne 0 ]; then
1324                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Agent"
1325                hayErrores=1
1326        fi
1327        popd   
1328        # Compilar OpenGnsys Client
1329        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Client"
1330        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
1331        make && mv ogAdmClient ../../../../client/shared/bin
1332        if [ $? -ne 0 ]; then
1333                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Client"
1334                hayErrores=1
1335        fi
1336        popd
1337
1338        return $hayErrores
1339}
1340
1341####################################################################
1342### Funciones de copia de la Interface de administración
1343####################################################################
1344
1345# Copiar carpeta de Interface
1346function copyInterfaceAdm ()
1347{
1348        local hayErrores=0
1349       
1350        # Crear carpeta y copiar Interface
1351        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
1352        cp -ar $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client/interfaceAdm
1353        if [ $? -ne 0 ]; then
1354                echoAndLog "${FUNCNAME}(): error while copying Administration Interface Folder"
1355                hayErrores=1
1356        fi
1357        chown $OPENGNSYS_CLIENT_USER:$OPENGNSYS_CLIENT_USER $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
1358        chmod 700 $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
1359
1360        return $hayErrores
1361}
1362
1363####################################################################
1364### Funciones instalacion cliente opengnsys
1365####################################################################
1366
1367function copyClientFiles()
1368{
1369        local errstatus=0
1370
1371        echoAndLog "${FUNCNAME}(): Copying OpenGnsys Client files."
1372        cp -a $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
1373        if [ $? -ne 0 ]; then
1374                errorAndLog "${FUNCNAME}(): error while copying client estructure"
1375                errstatus=1
1376        fi
1377        find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null
1378       
1379        echoAndLog "${FUNCNAME}(): Copying OpenGnsys Cloning Engine files."
1380        mkdir -p $INSTALL_TARGET/client/lib/engine/bin
1381        cp -a $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
1382        if [ $? -ne 0 ]; then
1383                errorAndLog "${FUNCNAME}(): error while copying engine files"
1384                errstatus=1
1385        fi
1386       
1387        if [ $errstatus -eq 0 ]; then
1388                echoAndLog "${FUNCNAME}(): client copy files success."
1389        else
1390                errorAndLog "${FUNCNAME}(): client copy files with errors"
1391        fi
1392
1393        return $errstatus
1394}
1395
1396
1397# Crear cliente OpenGnsys.
1398function clientCreate()
1399{
1400        #local FILENAME=ogLive-xenial-4.4.0-34-generic-r4999.iso        # 1.1.0-rc4
1401        local FILENAME=ogLive-xenial-4.8.0-39-generic-amd64-r5225.iso   # 1.1.0-rc5
1402        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
1403 
1404        # Descargar cliente, si es necesario.
1405        if [ -s $PROGRAMDIR/$FILENAME ]; then
1406                echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
1407                mv $PROGRAMDIR/$FILENAME $TARGETFILE
1408        else
1409                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
1410                $INSTALL_TARGET/bin/oglivecli download $FILENAME
1411        fi
1412        if [ ! -s $TARGETFILE ]; then
1413                errorAndLog "${FUNCNAME}(): Error loading $FILENAME"
1414                return 1
1415        fi
1416
1417        # Montar imagen, copiar cliente ogclient y desmontar.
1418        echoAndLog "${FUNCNAME}(): Installing ogLive Client"
1419        echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | \
1420                        $INSTALL_TARGET/bin/oglivecli install $FILENAME
1421        # Adaptar permisos.
1422        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/tftpboot/menu.lst
1423
1424        echoAndLog "${FUNCNAME}(): Client generation success"
1425}
1426
1427
1428# Configuración básica de servicios de OpenGnsys
1429function openGnsysConfigure()
1430{
1431        local i=0
1432        local dev=""
1433        local CONSOLEURL
1434
1435        echoAndLog "${FUNCNAME}(): Copying init files."
1436        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
1437        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default /etc/default/opengnsys
1438        # Deshabilitar servicios de BitTorrent si no están instalados.
1439        if [ ! -e /usr/bin/bttrack ]; then
1440                sed -i 's/RUN_BTTRACKER="yes"/RUN_BTTRACKER="no"/; s/RUN_BTSEEDER="yes"/RUN_BTSEEDER="no"/' \
1441                        /etc/default/opengnsys
1442        fi
1443        echoAndLog "${FUNCNAME}(): Creating cron files."
1444        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
1445        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
1446        echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
1447        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
1448
1449        echoAndLog "${FUNCNAME}(): Creating logrotate configuration file."
1450        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1451                $WORKDIR/opengnsys/server/etc/logrotate.tmpl > /etc/logrotate.d/opengnsys
1452
1453        echoAndLog "${FUNCNAME}(): Creating OpenGnsys config files."
1454        for dev in ${DEVICE[*]}; do
1455                if [ -n "${SERVERIP[i]}" ]; then
1456                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1457                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1458                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1459                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1460                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer/ogAdmServer.cfg > $INSTALL_TARGET/etc/ogAdmServer-$dev.cfg
1461                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1462                            -e "s/REPOKEY/$OPENGNSYS_REPOKEY/g" \
1463                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo/ogAdmRepo.cfg > $INSTALL_TARGET/etc/ogAdmRepo-$dev.cfg
1464                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1465                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1466                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1467                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1468                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent/ogAdmAgent.cfg > $INSTALL_TARGET/etc/ogAdmAgent-$dev.cfg
1469                        CONSOLEURL="https://${SERVERIP[i]}/opengnsys"
1470                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1471                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1472                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1473                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1474                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
1475                                $INSTALL_TARGET/www/controlacceso.php > $INSTALL_TARGET/www/controlacceso-$dev.php
1476                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1477                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
1478                                $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient/ogAdmClient.cfg > $INSTALL_TARGET/client/etc/ogAdmClient-$dev.cfg
1479                        if [ "$dev" == "$DEFAULTDEV" ]; then
1480                                OPENGNSYS_CONSOLEURL="$CONSOLEURL"
1481                        fi
1482                fi
1483                let i++
1484        done
1485        ln -f $INSTALL_TARGET/etc/ogAdmServer-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmServer.cfg
1486        ln -f $INSTALL_TARGET/etc/ogAdmRepo-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmRepo.cfg
1487        ln -f $INSTALL_TARGET/etc/ogAdmAgent-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmAgent.cfg
1488        ln -f $INSTALL_TARGET/client/etc/ogAdmClient-$DEFAULTDEV.cfg $INSTALL_TARGET/client/etc/ogAdmClient.cfg
1489        ln -f $INSTALL_TARGET/www/controlacceso-$DEFAULTDEV.php $INSTALL_TARGET/www/controlacceso.php
1490        chown root:root $INSTALL_TARGET/etc/{ogAdmServer,ogAdmAgent}*.cfg
1491        chmod 600 $INSTALL_TARGET/etc/{ogAdmServer,ogAdmAgent}*.cfg
1492        chown $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/controlacceso*.php
1493        chmod 600 $INSTALL_TARGET/www/controlacceso*.php
1494
1495        # Configuración del motor de clonación.
1496        # - Zona horaria del servidor.
1497        TZ=$(timedatectl status|awk -F"[:()]" '/Time.*zone/ {print $2}')
1498        cat << EOT >> $INSTALL_TARGET/client/etc/engine.cfg
1499# OpenGnsys Server timezone.
1500TZ="${TZ// /}"
1501EOT
1502
1503        # Revisar permisos generales.
1504        if [ -x $INSTALL_TARGET/bin/checkperms ]; then
1505                echoAndLog "${FUNCNAME}(): Checking permissions."
1506                OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENT_USER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" $INSTALL_TARGET/bin/checkperms
1507        fi
1508
1509        # Evitar inicio de duplicado en Ubuntu 14.04 (Upstart y SysV Init).
1510        if [ -f /etc/init/${MYSQLSERV}.conf -a -n "$(which initctl 2>/dev/null)" ]; then
1511                service=$MYSQLSERV
1512                $DISABLESERVICE
1513        fi
1514
1515        echoAndLog "${FUNCNAME}(): Starting OpenGnsys services."
1516        service="opengnsys"
1517        $ENABLESERVICE; $STARTSERVICE
1518}
1519
1520
1521#####################################################################
1522#######  Función de resumen informativo de la instalación
1523#####################################################################
1524
1525function installationSummary()
1526{
1527        # Crear fichero de versión y revisión, si no existe.
1528        local VERSIONFILE="$INSTALL_TARGET/doc/VERSION.txt"
1529        [ -f $VERSIONFILE ] || echo "OpenGnsys Server" >$VERSIONFILE
1530        # Incluir datos de revisión, si se está instaladno desde el repositorio
1531        # de código o si no está incluida en el fichero de versión.
1532        if [ $USESVN -eq 1 ] || [ -z "$(awk '$3~/r[0-9]*/ {print}' $VERSIONFILE)" ]; then
1533                local REVISION=$(LANG=C svn info $SVN_URL|awk '/Rev:/ {print "r"$4}')
1534                perl -pi -e "s/($| r[0-9]*)/ $REVISION/" $VERSIONFILE
1535        fi
1536
1537        # Mostrar información.
1538        echo
1539        echoAndLog "OpenGnsys Installation Summary"
1540        echo       "=============================="
1541        echoAndLog "Project version:                  $(cat $VERSIONFILE 2>/dev/null)"
1542        echoAndLog "Installation directory:           $INSTALL_TARGET"
1543        echoAndLog "Installation log file:            $LOG_FILE"
1544        echoAndLog "Repository directory:             $INSTALL_TARGET/images"
1545        echoAndLog "DHCP configuration directory:     $DHCPCFGDIR"
1546        echoAndLog "TFTP configuration directory:     $TFTPCFGDIR"
1547        echoAndLog "Samba configuration directory:    $SAMBACFGDIR"
1548        echoAndLog "Web Console URL:                  $OPENGNSYS_CONSOLEURL"
1549        echoAndLog "Web Console access data:          specified in installer script"
1550        if grep -q "^RUN_BTTRACK.*no" /etc/default/opengnsys; then
1551                echoAndLog "BitTorrent service is disabled."
1552        fi
1553        echo
1554        echoAndLog "Post-Installation Instructions:"
1555        echo       "==============================="
1556        echoAndLog "Firewall service has been disabled and SELinux mode set to"
1557        echoAndLog "   permissive during OpenGnsys installation. Please check"
1558        echoAndLog "   ${FIREWALLSERV:-firewall} and SELinux configuration, if needed."
1559        echoAndLog "It's strongly recommended to synchronize this server with an NTP server."
1560        echoAndLog "Review or edit all configuration files."
1561        echoAndLog "Insert DHCP configuration data and restart service."
1562        echoAndLog "Optional: Log-in as Web Console admin user."
1563        echoAndLog " - Review default Organization data and assign access to users."
1564        echoAndLog "Log-in as Web Console organization user."
1565        echoAndLog " - Insert OpenGnsys data (labs, computers, menus, etc)."
1566echo
1567}
1568
1569
1570
1571#####################################################################
1572####### Proceso de instalación de OpenGnsys
1573#####################################################################
1574
1575echoAndLog "OpenGnsys installation begins at $(date)"
1576pushd $WORKDIR
1577
1578# Detectar datos iniciales de auto-configuración del instalador.
1579autoConfigure
1580
1581# Detectar parámetros de red y comprobar si hay conexión.
1582getNetworkSettings
1583if [ $? -ne 0 ]; then
1584        errorAndLog "Error reading default network settings."
1585        exit 1
1586fi
1587checkNetworkConnection
1588if [ $? -ne 0 ]; then
1589        errorAndLog "Error connecting to server. Causes:"
1590        errorAndLog " - Network is unreachable, review devices parameters."
1591        errorAndLog " - You are inside a private network, configure the proxy service."
1592        errorAndLog " - Server is temporally down, try agian later."
1593        exit 1
1594fi
1595
1596# Detener servicios de OpenGnsys, si están activos previamente.
1597[ -f /etc/init.d/opengnsys ] && /etc/init.d/opengnsys stop
1598
1599# Actualizar repositorios
1600updatePackageList
1601
1602# Instalación de dependencias (paquetes de sistema operativo).
1603declare -a notinstalled
1604checkDependencies DEPENDENCIES notinstalled
1605if [ $? -ne 0 ]; then
1606        installDependencies notinstalled
1607        if [ $? -ne 0 ]; then
1608                echoAndLog "Error while installing some dependeces, please verify your server installation before continue"
1609                exit 1
1610        fi
1611fi
1612if [ -n "$INSTALLEXTRADEPS" ]; then
1613        echoAndLog "Installing extra dependencies"
1614        for (( i=0; i<${#INSTALLEXTRADEPS[*]}; i++ )); do
1615                eval ${INSTALLEXTRADEPS[i]}
1616        done
1617fi     
1618
1619# Detectar datos de auto-configuración después de instalar paquetes.
1620autoConfigurePost
1621
1622# Arbol de directorios de OpenGnsys.
1623createDirs ${INSTALL_TARGET}
1624if [ $? -ne 0 ]; then
1625        errorAndLog "Error while creating directory paths!"
1626        exit 1
1627fi
1628
1629# Si es necesario, descarga el repositorio de código en directorio temporal
1630if [ $USESVN -eq 1 ]; then
1631        svnExportCode $SVN_URL
1632        if [ $? -ne 0 ]; then
1633                errorAndLog "Error while getting code from svn"
1634                exit 1
1635        fi
1636else
1637        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
1638fi
1639
1640# Compilar código fuente de los servicios de OpenGnsys.
1641servicesCompilation
1642if [ $? -ne 0 ]; then
1643        errorAndLog "Error while compiling OpenGnsys services"
1644        exit 1
1645fi
1646
1647# Copiar carpeta Interface entre administración y motor de clonación.
1648copyInterfaceAdm
1649if [ $? -ne 0 ]; then
1650        errorAndLog "Error while copying Administration Interface"
1651        exit 1
1652fi
1653
1654# Configuración de TFTP.
1655tftpConfigure
1656
1657# Configuración de Samba.
1658smbConfigure
1659if [ $? -ne 0 ]; then
1660        errorAndLog "Error while configuring Samba server!"
1661        exit 1
1662fi
1663
1664# Configuración de Rsync.
1665rsyncConfigure
1666
1667# Configuración ejemplo DHCP.
1668dhcpConfigure
1669if [ $? -ne 0 ]; then
1670        errorAndLog "Error while copying your dhcp server files!"
1671        exit 1
1672fi
1673
1674# Copiar ficheros de servicios OpenGnsys Server.
1675copyServerFiles ${INSTALL_TARGET}
1676if [ $? -ne 0 ]; then
1677        errorAndLog "Error while copying the server files!"
1678        exit 1
1679fi
1680INSTVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt)
1681
1682# Instalar base de datos de OpenGnsys Admin.
1683isInArray notinstalled "mysql-server" || isInArray notinstalled "mariadb-server"
1684if [ $? -eq 0 ]; then
1685        # Habilitar gestor de base de datos (MySQL, si falla, MariaDB).
1686        service=$MYSQLSERV
1687        $ENABLESERVICE
1688        if [ $? != 0 ]; then
1689                service=$MARIADBSERV
1690                $ENABLESERVICE
1691        fi
1692        # Activar gestor de base de datos.
1693        $STARTSERVICE
1694        # Asignar clave del usuario "root".
1695        mysqlSetRootPassword "${MYSQL_ROOT_PASSWORD}"
1696else
1697        # Si ya está instalado el gestor de bases de datos, obtener clave de "root",
1698        mysqlGetRootPassword
1699fi
1700
1701mysqlTestConnection "${MYSQL_ROOT_PASSWORD}"
1702if [ $? -ne 0 ]; then
1703        errorAndLog "Error while connection to mysql"
1704        exit 1
1705fi
1706mysqlDbExists ${OPENGNSYS_DATABASE}
1707if [ $? -ne 0 ]; then
1708        echoAndLog "Creating Web Console database"
1709        mysqlCreateDb ${OPENGNSYS_DATABASE}
1710        if [ $? -ne 0 ]; then
1711                errorAndLog "Error while creating Web Console database"
1712                exit 1
1713        fi
1714else
1715        echoAndLog "Web Console database exists, ommiting creation"
1716fi
1717
1718mysqlCheckUserExists ${OPENGNSYS_DB_USER}
1719if [ $? -ne 0 ]; then
1720        echoAndLog "Creating user in database"
1721        mysqlCreateAdminUserToDb ${OPENGNSYS_DATABASE} ${OPENGNSYS_DB_USER} "${OPENGNSYS_DB_PASSWD}"
1722        if [ $? -ne 0 ]; then
1723                errorAndLog "Error while creating database user"
1724                exit 1
1725        fi
1726
1727fi
1728
1729mysqlCheckDbIsEmpty ${OPENGNSYS_DATABASE}
1730if [ $? -eq 0 ]; then
1731        echoAndLog "Creating tables..."
1732        if [ -f $WORKDIR/$OPENGNSYS_DB_CREATION_FILE ]; then
1733                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_CREATION_FILE
1734        else
1735                errorAndLog "Unable to locate $WORKDIR/$OPENGNSYS_DB_CREATION_FILE!!"
1736                exit 1
1737        fi
1738else
1739        # Si existe fichero ogBDAdmin-VersLocal-VersRepo.sql; aplicar cambios.
1740        REPOVERSION=$(awk '{print $2}' $WORKDIR/opengnsys/doc/VERSION.txt)
1741        OPENGNSYS_DB_UPDATE_FILE="opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
1742        if [ -f $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE ]; then
1743                echoAndLog "Updating tables from version $INSTVERSION to $REPOVERSION"
1744                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE
1745        else
1746                echoAndLog "Database unchanged."
1747        fi
1748fi
1749# Eliminar fichero temporal con credenciales de acceso a MySQL.
1750rm -f $TMPMYCNF
1751
1752# Copiando páqinas web.
1753installWebFiles
1754# Descargar/descomprimir archivos descargables.
1755installDownloadableFiles
1756# Generar páqinas web de documentación de la API
1757makeDoxygenFiles
1758
1759# Creando configuración de Apache.
1760installWebConsoleApacheConf $INSTALL_TARGET $APACHECFGDIR
1761if [ $? -ne 0 ]; then
1762        errorAndLog "Error configuring Apache for OpenGnsys Admin"
1763        exit 1
1764fi
1765
1766popd
1767
1768# Crear la estructura de los accesos al servidor desde el cliente (shared)
1769copyClientFiles
1770if [ $? -ne 0 ]; then
1771        errorAndLog "Error creating client structure"
1772fi
1773
1774# Crear la estructura del cliente de OpenGnsys.
1775clientCreate
1776if [ $? -ne 0 ]; then
1777        errorAndLog "Error creating client"
1778        exit 1
1779fi
1780
1781# Configuración de servicios de OpenGnsys
1782openGnsysConfigure
1783
1784# Mostrar sumario de la instalación e instrucciones de post-instalación.
1785installationSummary
1786
1787#rm -rf $WORKDIR
1788echoAndLog "OpenGnsys installation finished at $(date)"
1789exit 0
1790
Note: See TracBrowser for help on using the repository browser.