source: installer/opengnsys_installer_devel_esxi.sh @ 17dc359

configure-oglivelgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacion
Last change on this file since 17dc359 was 17dc359, checked in by Natalia Serrano <natalia.serrano@…>, 17 months ago

more debug "server connectivity"

  • Property mode set to 100755
File size: 71.3 KB
Line 
1#!/bin/bash
2
3#####################################################################
4####### Script instalador OpenGnsys
5####### Autor: Luis Guillén <lguillen@unizar.es>
6#####################################################################
7
8
9#####################################################################
10####### Funciones de configuración
11#####################################################################
12
13MY_BRANCH=$1
14
15# Devuelve en la variable PASSWORD la clave introducida por el usuario (o la indicada por defecto)
16function enterPassword ()
17{
18        local PASSWORD2
19        local DEFAULT_PASSWORD="$1"
20
21        while : ; do
22                stty -echo
23                read -r PASSWORD
24                stty echo
25                if [ -z "$PASSWORD" ]; then
26                        # Si esta vacio ponemos el valor por defecto
27                        PASSWORD="${PASSWORD:-$DEFAULT_PASSWORD}"
28                        break
29                else
30                        if [ -n "${PASSWORD//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico
31                                echo -e "\\aERROR: Password must be alphanumeric, try again..."
32                        else
33                                echo -n -e "\\nConfirm password: "
34                                stty -echo
35                                read -r PASSWORD2
36                                stty echo
37                                if [ "$PASSWORD" == "$PASSWORD2" ]; then
38                                        break
39                                else
40                                        echo -e "\\aERROR: Passwords don't match, try again."
41                                fi
42                        fi
43                fi
44                echo -n -e "Please, enter a new password (${DEFAULT_PASSWORD}): "
45        done
46}
47
48# Recoge los datos de configuración introducidos por el usuario.
49function userData ()
50{
51        ####  AVISO: Puede editar configuración de acceso por defecto.
52        ####  WARNING: Edit default access configuration if you wish.
53        DEFAULT_MYSQL_ROOT_PASSWORD="passwordroot"      # Clave por defecto root de MySQL
54        DEFAULT_OPENGNSYS_DB_USER="usuog"               # Usuario por defecto de acceso a la base de datos
55        DEFAULT_OPENGNSYS_DB_PASSWD="passusuog"         # Clave por defecto de acceso a la base de datos
56        DEFAULT_OPENGNSYS_CLIENT_PASSWD="og"            # Clave por defecto de acceso del cliente
57        DEFAULT_OGLIVE="ogLive-focal-5.11.0-22-generic-amd64-r20210413.992ebb9.iso"     # Cliente ogLive
58
59        echo -e "\\nOpenGnsys Installation"
60        echo "=============================="
61
62        if [[ $- =~ s ]]; then
63                echo -e "\\nNot interactive mode: setting default configuration values.\\n"
64                MYSQL_ROOT_PASSWORD="$DEFAULT_MYSQL_ROOT_PASSWORD"
65                OPENGNSYS_DB_USER="$DEFAULT_OPENGNSYS_DB_USER"
66                OPENGNSYS_DB_PASSWD="$DEFAULT_OPENGNSYS_DB_PASSWD"
67                OPENGNSYS_CLIENT_PASSWD="$DEFAULT_OPENGNSYS_CLIENT_PASSWD"
68                OGLIVE="$DEFAULT_OGLIVE"
69                return
70        fi
71
72        # Clave root de MySQL
73        echo -n -e "\\nEnter root password for MySQL (${DEFAULT_MYSQL_ROOT_PASSWORD}): "
74        enterPassword "$DEFAULT_MYSQL_ROOT_PASSWORD"
75        MYSQL_ROOT_PASSWORD="$PASSWORD"
76
77        # Usuario de acceso a la base de datos
78        while : ; do
79                echo -n -e "\\n\\nEnter username for OpenGnsys console (${DEFAULT_OPENGNSYS_DB_USER}): "
80                read -r OPENGNSYS_DB_USER
81                if [ -n "${OPENGNSYS_DB_USER//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico
82                        echo -e "\\aERROR: Must be alphanumeric, try again..."
83                else
84                        # Si esta vacio ponemos el valor por defecto
85                        OPENGNSYS_DB_USER="${OPENGNSYS_DB_USER:-$DEFAULT_OPENGNSYS_DB_USER}"
86                        break
87                fi
88        done
89
90        # Clave de acceso a la base de datos
91        echo -n -e "\\nEnter password for OpenGnsys console (${DEFAULT_OPENGNSYS_DB_PASSWD}): "
92        enterPassword "$DEFAULT_OPENGNSYS_DB_PASSWD"
93        OPENGNSYS_DB_PASSWD="$PASSWORD"
94
95        # Clave de acceso del cliente
96        echo -n -e "\\n\\nEnter root password for OpenGnsys client (${DEFAULT_OPENGNSYS_CLIENT_PASSWD}): "
97        enterPassword "$DEFAULT_OPENGNSYS_CLIENT_PASSWD"
98        OPENGNSYS_CLIENT_PASSWD="$PASSWORD"
99        unset PASSWORD
100
101        # Selección de clientes ogLive para descargar.
102        while : ; do
103                echo -e "\\n\\nChoose ogLive client to install."
104                echo -e "1) Kernel 5.11, 64-bit, EFI-compatible"
105                echo -e "2) Kernel 3.2, 32-bit"
106                echo -e "3) Both"
107                echo -n -e "Please, type a valid number (1): "
108                read -r OPT
109                case "$OPT" in
110                        1|"")   OGLIVE="$DEFAULT_OGLIVE"
111                                break ;;
112                        2)      OGLIVE="ogLive-precise-3.2.0-23-generic-r5159.iso"
113                                break ;;
114                        3)      OGLIVE=" $DEFAULT_OGLIVE ogLive-precise-3.2.0-23-generic-r5159.iso";
115                                break ;;
116                        *)      echo -e "\\aERROR: unknown option, try again."
117                esac
118        done
119
120        echo -e "\\n=============================="
121}
122
123# Asigna valores globales de configuración para el script.
124function globalSetup ()
125{
126        PROGRAMDIR=$(readlink -e "$(dirname "$0")")
127        PROGRAMNAME=$(basename "$0")
128
129        # Comprobar si se ha descargado el paquete comprimido (REMOTE=0) o sólo el instalador (REMOTE=1).
130        OPENGNSYS_SERVER="opengnsys.es"
131        DOWNLOADURL="https://$OPENGNSYS_SERVER/trac/downloads"
132        if [ -d "$PROGRAMDIR/../installer" ]; then
133                echo REMOTE=0
134                REMOTE=0
135        else
136                echo REMOTE=1
137                REMOTE=1
138        fi
139        BRANCH=$1
140        if [[ -z $BRANCH ]]; then
141                BRANCH="main"
142        fi
143        API_URL="https://api.github.com/repos/opengnsys/OpenGnsys"
144        GIT_REPO="ssh://git@ognproject.evlt.uma.es:21987/opengnsys/opengnsys.git"
145
146        # Directorios de instalación y destino de OpenGnsys.
147        WORKDIR=/tmp/opengnsys_installer
148        INSTALL_TARGET=/opt/opengnsys
149        PATH=$PATH:$INSTALL_TARGET/bin
150
151        # Registro de incidencias.
152        OGLOGFILE=$INSTALL_TARGET/log/${PROGRAMNAME%.sh}.log
153        LOG_FILE=/tmp/$(basename $OGLOGFILE)
154
155        # Usuario del cliente para acceso remoto.
156        OPENGNSYS_CLIENT_USER="opengnsys"
157        # Nombre de la base datos y fichero SQL para su creación.
158        OPENGNSYS_DATABASE="ogAdmBD"
159        OPENGNSYS_DB_CREATION_FILE=opengnsys/admin/Database/${OPENGNSYS_DATABASE}.sql
160
161        # Set Default net
162        DHCPNET=${DHCPNET:-"NONE"}
163        echo Default Network is $DHCPNET
164}
165
166# Generar variables de configuración del instalador
167# Variables globales:
168# - OSDISTRIB, OSVERSION - tipo y versión de la distribución GNU/Linux
169# - DEPENDENCIES - array de dependencias que deben estar instaladas
170# - UPDATEPKGLIST, INSTALLPKGS, CHECKPKGS - comandos para gestión de paquetes
171# - INSTALLEXTRADEPS - instalar dependencias no incluidas en la distribución
172# - STARTSERVICE, ENABLESERVICE - iniciar y habilitar un servicio
173# - STOPSERVICE, DISABLESERVICE - parar y deshabilitar un servicio
174# - APACHESERV, APACHECFGDIR, APACHESITESDIR, APACHEUSER, APACHEGROUP - servicio y configuración de Apache
175# - APACHEENABLEMODS, APACHEENABLESSL, APACHEMAKECERT - habilitar módulos y certificado SSL
176# - APACHEENABLEOG, APACHEOGSITE, - habilitar sitio web de OpenGnsys
177# - PHPFPMSERV - servicio PHP FastCGI Process Manager para Apache
178# - INETDSERV - servicio Inetd
179# - DHCPSERV, DHCPCFGDIR - servicio y configuración de DHCP
180# - MYSQLSERV, TMPMYCNF - servicio MySQL y fichero temporal con credenciales de acceso
181# - MARIADBSERV - servicio MariaDB (sustituto de MySQL en algunas distribuciones)
182# - RSYNCSERV, RSYNCCFGDIR - servicio y configuración de Rsync
183# - SAMBASERV, SAMBACFGDIR - servicio y configuración de Samba
184# - TFTPSERV, TFTPCFGDIR - servicio y configuración de TFTP/PXE
185function autoConfigure()
186{
187# Detectar sistema operativo del servidor (compatible con fichero os-release y con LSB).
188if [ -f /etc/os-release ]; then
189        source /etc/os-release
190        OSDISTRIB="$ID"
191        OSVERSION="$VERSION_ID"
192else
193        OSDISTRIB=$(lsb_release -is 2>/dev/null)
194        OSVERSION=$(lsb_release -rs 2>/dev/null)
195fi
196# Convertir distribución a minúsculas y obtener solo el 1er número de versión.
197OSDISTRIB="${OSDISTRIB,,}"
198OSVERSION="${OSVERSION%%.*}"
199
200# Configuración según la distribución GNU/Linux (usar minúsculas).
201case "$OSDISTRIB" in
202        ubuntu|debian|linuxmint)
203                DEPENDENCIES=( subversion apache2 php php-ldap php-fpm mysql-server php-mysql isc-dhcp-server bittorrent tftp-hpa tftpd-hpa xinetd build-essential g++-multilib libmysqlclient-dev wget curl doxygen graphviz bittornado ctorrent samba rsync unzip netpipes debootstrap schroot squashfs-tools btrfs-tools procps arp-scan realpath php-curl gettext moreutils jq wakeonlan udpcast libev-dev libjansson-dev libssl-dev shim-signed grub-efi-amd64-signed gawk libdbi-dev libdbi1 libdbd-mysql liblz4-tool git stunnel4 )
204                UPDATEPKGLIST="apt-get update"
205                INSTALLPKG="apt-get -y install --force-yes"
206                CHECKPKG="dpkg -s \$package 2>/dev/null | grep Status | grep -qw install"
207                if which service &>/dev/null; then
208                        STARTSERVICE="eval service \$service restart"
209                        STOPSERVICE="eval service \$service stop"
210                else
211                        STARTSERVICE="eval /etc/init.d/\$service restart"
212                        STOPSERVICE="eval /etc/init.d/\$service stop"
213                fi
214                ENABLESERVICE="eval update-rc.d \$service defaults"
215                DISABLESERVICE="eval update-rc.d \$service disable"
216                APACHESERV=apache2
217                APACHECFGDIR=/etc/apache2
218                APACHESITESDIR=sites-available
219                APACHEOGSITE=opengnsys
220                APACHEUSER="www-data"
221                APACHEGROUP="www-data"
222                APACHEENABLEMODS="a2enmod ssl rewrite proxy_fcgi fastcgi actions alias"
223                APACHEENABLESSL="a2ensite default-ssl"
224                APACHEENABLEOG="a2ensite $APACHEOGSITE"
225                APACHEMAKECERT="make-ssl-cert generate-default-snakeoil --force-overwrite"
226                DHCPSERV=isc-dhcp-server
227                DHCPCFGDIR=/etc/dhcp
228                INETDSERV=xinetd
229                INETDCFGDIR=/etc/xinetd.d
230                MYSQLSERV=mysql
231                MYSQLCFGDIR=/etc/mysql/mysql.conf.d
232                MARIADBSERV=mariadb
233                PHPFPMSERV=php-fpm
234                RSYNCSERV=rsync
235                RSYNCCFGDIR=/etc
236                SAMBASERV=smbd
237                SAMBACFGDIR=/etc/samba
238                TFTPCFGDIR=/var/lib/tftpboot
239                LOCAL_CERTS_DIR=/usr/local/share/ca-certificates
240                UPDATE_CA_CMD=update-ca-certificates
241                STUNNEL_CAPATH=/etc/ssl/certs
242                ;;
243        fedora|centos)
244                DEPENDENCIES=( subversion httpd mod_ssl php-ldap php-fpm mysql-server mysql-devel mysql-devel.i686 php-mysql dhcp tftp-server tftp xinetd binutils gcc gcc-c++ glibc-devel glibc-devel.i686 glibc-static glibc-static.i686 libstdc++-devel.i686 make wget curl doxygen graphviz ctorrent samba samba-client rsync unzip debootstrap schroot squashfs-tools python-crypto arp-scan procps-ng gettext moreutils jq net-tools udpcast libev-devel jansson-devel openssl-devel shim-x64 grub2-efi-x64 grub2-efi-x64-modules gawk libdbi-devel libdbi libdbi-dbd-mysql http://ftp.altlinux.org/pub/distributions/ALTLinux/5.1/branch/$(arch)/RPMS.classic/netpipes-4.2-alt1.$(arch).rpm )
245                [ "$OSDISTRIB" == "centos" ] && UPDATEPKGLIST="yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-$OSVERSION.noarch.rpm http://rpms.remirepo.net/enterprise/remi-release-$OSVERSION.rpm"
246                INSTALLEXTRADEPS=( 'pushd /tmp; wget -t3 http://ftp.acc.umu.se/mirror/bittornado/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' )
247                INSTALLPKG="yum install -y libstdc++ libstdc++.i686"
248                CHECKPKG="rpm -q --quiet \$package"
249                SYSTEMD=$(which systemctl 2>/dev/null)
250                if [ -n "$SYSTEMD" ]; then
251                        STARTSERVICE="eval systemctl start \$service.service"
252                        STOPSERVICE="eval systemctl stop \$service.service"
253                        ENABLESERVICE="eval systemctl enable \$service.service"
254                        DISABLESERVICE="eval systemctl disable \$service.service"
255                else
256                        STARTSERVICE="eval service \$service start"
257                        STOPSERVICE="eval service \$service stop"
258                        ENABLESERVICE="eval chkconfig \$service on"
259                        DISABLESERVICE="eval chkconfig \$service off"
260                fi
261                APACHESERV=httpd
262                APACHECFGDIR=/etc/httpd/conf.d
263                APACHEOGSITE=opengnsys.conf
264                APACHEUSER="apache"
265                APACHEGROUP="apache"
266                APACHEREWRITEMOD="sed -i '/rewrite/s/^#//' $APACHECFGDIR/../*.conf"
267                DHCPSERV=dhcpd
268                DHCPCFGDIR=/etc/dhcp
269                INETDSERV=xinetd
270                INETDCFGDIR=/etc/xinetd.d
271                MYSQLSERV=mysqld
272                MYSQLCFGDIR=/etc/my.cnf.d
273                MARIADBSERV=mariadb
274                PHPFPMSERV=php-fpm
275                RSYNCSERV=rsync
276                RSYNCCFGDIR=/etc
277                SAMBASERV=smb
278                SAMBACFGDIR=/etc/samba
279                TFTPSERV=tftp
280                TFTPCFGDIR=/var/lib/tftpboot
281                LOCAL_CERTS_DIR=/etc/pki/ca-trust/source/anchors
282                UPDATE_CA_CMD=update-ca-trust
283                STUNNEL_CAPATH=/etc/pki/tls/certs
284                ;;
285        "")     echo "ERROR: Unknown Linux distribution, please install \"lsb_release\" command."
286                exit 1 ;;
287        *)      echo "ERROR: Distribution not supported by OpenGnsys."
288                exit 1 ;;
289esac
290
291# Fichero de credenciales de acceso a MySQL.
292TMPMYCNF=/tmp/.my.cnf.$$
293}
294
295
296# Modificar variables de configuración tras instalar paquetes del sistema.
297function autoConfigurePost()
298{
299local f MKNETDIR
300
301# Configuraciones específicas para Samba y TFTP en Debian 6.
302[ -z "$SYSTEMD" -a ! -e /etc/init.d/$SAMBASERV ] && SAMBASERV=samba
303[ ! -e $TFTPCFGDIR ] && TFTPCFGDIR=/srv/tftp
304
305# Preparar arranque en red con Grub.
306for f in grub-mknetdir grub2-mknetdir; do
307        if which $f &>/dev/null; then MKNETDIR=$f; fi
308done
309$MKNETDIR --net-directory=$TFTPCFGDIR --subdir=grub
310}
311
312
313# Cargar lista de paquetes del sistema y actualizar algunas variables de configuración
314# dependiendo de la versión instalada.
315function updatePackageList()
316{
317local DHCPVERSION PHP7VERSION
318
319# Si es necesario, actualizar la lista de paquetes disponibles.
320[ -n "$UPDATEPKGLIST" ] && eval $UPDATEPKGLIST
321
322# Configuración personallizada de algunos paquetes.
323case "$OSDISTRIB" in
324        ubuntu|linuxmint)       # Postconfiguación personalizada para Ubuntu.
325                # Configuración para DHCP v3.
326                DHCPVERSION=$(apt-cache show $(apt-cache pkgnames|egrep "dhcp.?-server$") | \
327                              awk '/Version/ {print substr($2,1,1);}' | \
328                              sort -n | tail -1)
329                if [ $DHCPVERSION = 3 ]; then
330                        DEPENDENCIES=( ${DEPENDENCIES[@]/isc-dhcp-server/dhcp3-server} )
331                        DHCPSERV=dhcp3-server
332                        DHCPCFGDIR=/etc/dhcp3
333                fi
334                # Configuración para PHP 7 en Ubuntu.
335                if [ -z "$(apt-cache pkgnames php7)" ]; then
336                        eval $INSTALLPKG software-properties-common
337                        add-apt-repository -y ppa:ondrej/php
338                        eval $UPDATEPKGLIST
339                        PHP7VERSION=$(apt-cache pkgnames php7 | sort | head -1)
340                        PHPFPMSERV="${PHP7VERSION}-fpm"
341                        DEPENDENCIES=( ${DEPENDENCIES[@]//php/$PHP7VERSION} )
342                fi
343                # Adaptar dependencias para libmysqlclient.
344                [ -z "$(apt-cache pkgnames libmysqlclient-dev)" ] && [ -n "$(apt-cache pkgnames libmysqlclient15)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//libmysqlclient-dev/libmysqlclient15} )
345                # Paquetes correctos en versiones nuevas.
346                [ -z "$(apt-cache pkgnames realpath)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//realpath/coreutils} )
347                [ -z "$(apt-cache pkgnames btrfs-tools)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//btrfs-tools/btrfs-progs} )
348                [ -z "$(apt-cache pkgnames bittorrent)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//bittorrent/} )
349                [ -z "$(apt-cache pkgnames bittornado)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//bittornado/} )
350                ;;
351        centos) # Postconfiguación personalizada para CentOS.
352                # Configuración para PHP 7.
353                PHP7VERSION=$(yum list -q php7\* 2>/dev/null | awk -F. '/^php/ {print $1; exit;}')
354                PHPFPMSERV="${PHP7VERSION}-${PHPFPMSERV}"
355                DEPENDENCIES=( ${PHP7VERSION} ${DEPENDENCIES[@]//php/$PHP7VERSION-php} )
356                # Cambios a aplicar a partir de CentOS 7.
357                if [ $OSVERSION -ge 7 ]; then
358                        # Sustituir MySQL por MariaDB.
359                        DEPENDENCIES=( ${DEPENDENCIES[*]/mysql-/mariadb-} )
360                        # Instalar ctorrent de EPEL para CentOS 6 (no disponible en CentOS 7).
361                        DEPENDENCIES=( ${DEPENDENCIES[*]/ctorrent/http://dl.fedoraproject.org/pub/epel/6/$(arch)/Packages/c/ctorrent-1.3.4-14.dnh3.3.2.el6.$(arch).rpm} )
362                fi
363                ;;
364        fedora) # Postconfiguación personalizada para Fedora.
365                # Incluir paquetes específicos.
366                DEPENDENCIES=( ${DEPENDENCIES[@]} btrfs-progs )
367                # Sustituir MySQL por MariaDB a partir de Fedora 20.
368                [ $OSVERSION -ge 20 ] && DEPENDENCIES=( ${DEPENDENCIES[*]/mysql-/mariadb-} )
369                ;;
370esac
371}
372
373
374#####################################################################
375####### Algunas funciones útiles de propósito general:
376#####################################################################
377
378function getDateTime()
379{
380        date "+%Y%m%d-%H%M%S"
381}
382
383# Escribe a fichero y muestra por pantalla
384function echoAndLog()
385{
386        local DATETIME=`getDateTime`
387        echo "$1"
388        echo "$DATETIME;$SSH_CLIENT;$1" >> $LOG_FILE
389}
390
391# Escribe a fichero y muestra mensaje de error
392function errorAndLog()
393{
394        local DATETIME=`getDateTime`
395        echo "ERROR: $1"
396        echo "$DATETIME;$SSH_CLIENT;ERROR: $1" >> $LOG_FILE
397}
398
399# Escribe a fichero y muestra mensaje de aviso
400function warningAndLog()
401{
402        local DATETIME=`getDateTime`
403        echo "Warning: $1"
404        echo "$DATETIME;$SSH_CLIENT;Warning: $1" >> $LOG_FILE
405}
406
407# Comprueba si el elemento pasado en $2 está en el array $1
408function isInArray()
409{
410        if [ $# -ne 2 ]; then
411                errorAndLog "${FUNCNAME}(): invalid number of parameters"
412                exit 1
413        fi
414
415        local deps
416        local is_in_array=1
417        local element="$2"
418
419        echoAndLog "${FUNCNAME}(): checking if $2 is in $1"
420        eval "deps=( \"\${$1[@]}\" )"
421
422        # Copia local del array del parámetro 1.
423        for (( i = 0 ; i < ${#deps[@]} ; i++ )); do
424                if [ "${deps[$i]}" = "${element}" ]; then
425                        echoAndLog "isInArray(): $element found in array"
426                        is_in_array=0
427                fi
428        done
429
430        if [ $is_in_array -ne 0 ]; then
431                echoAndLog "${FUNCNAME}(): $element NOT found in array"
432        fi
433
434        return $is_in_array
435}
436
437
438#####################################################################
439####### Funciones de manejo de paquetes Debian
440#####################################################################
441
442function checkPackage()
443{
444        package=$1
445        if [ -z $package ]; then
446                errorAndLog "${FUNCNAME}(): parameter required"
447                exit 1
448        fi
449        echoAndLog "${FUNCNAME}(): checking if package $package exists"
450        eval $CHECKPKG
451        if [ $? -eq 0 ]; then
452                echoAndLog "${FUNCNAME}(): package $package exists"
453                return 0
454        else
455                echoAndLog "${FUNCNAME}(): package $package doesn't exists"
456                return 1
457        fi
458}
459
460# Recibe array con dependencias
461# por referencia deja un array con las dependencias no resueltas
462# devuelve 1 si hay alguna dependencia no resuelta
463function checkDependencies()
464{
465        if [ $# -ne 2 ]; then
466                errorAndLog "${FUNCNAME}(): invalid number of parameters"
467                exit 1
468        fi
469
470        echoAndLog "${FUNCNAME}(): checking dependences"
471        uncompletedeps=0
472
473        # copia local del array del parametro 1
474        local deps
475        eval "deps=( \"\${$1[@]}\" )"
476
477        declare -a local_notinstalled
478
479        for (( i = 0 ; i < ${#deps[@]} ; i++ ))
480        do
481                checkPackage ${deps[$i]}
482                if [ $? -ne 0 ]; then
483                        local_notinstalled[$uncompletedeps]=$package
484                        let uncompletedeps=uncompletedeps+1
485                fi
486        done
487
488        # relleno el array especificado en $2 por referencia
489        for (( i = 0 ; i < ${#local_notinstalled[@]} ; i++ ))
490        do
491                eval "${2}[$i]=${local_notinstalled[$i]}"
492        done
493
494        # retorna el numero de paquetes no resueltos
495        echoAndLog "${FUNCNAME}(): dependencies uncompleted: $uncompletedeps"
496        return $uncompletedeps
497}
498
499# Recibe un array con las dependencias y lo instala
500function installDependencies()
501{
502        if [ $# -ne 1 ]; then
503                errorAndLog "${FUNCNAME}(): invalid number of parameters"
504                exit 1
505        fi
506        echoAndLog "${FUNCNAME}(): installing uncompleted dependencies"
507
508        # copia local del array del parametro 1
509        local deps
510        eval "deps=( \"\${$1[@]}\" )"
511
512        local string_deps=""
513        for (( i = 0 ; i < ${#deps[@]} ; i++ ))
514        do
515                string_deps="$string_deps ${deps[$i]}"
516        done
517
518        if [ -z "${string_deps}" ]; then
519                errorAndLog "${FUNCNAME}(): array of dependeces is empty"
520                exit 1
521        fi
522
523        OLD_DEBIAN_FRONTEND=$DEBIAN_FRONTEND            # Debian/Ubuntu
524        export DEBIAN_FRONTEND=noninteractive
525
526        echoAndLog "${FUNCNAME}(): now $string_deps will be installed"
527        eval $INSTALLPKG $string_deps
528        if [ $? -ne 0 ]; then
529                errorAndLog "${FUNCNAME}(): error installing dependencies"
530                return 1
531        fi
532
533        DEBIAN_FRONTEND=$OLD_DEBIAN_FRONTEND            # Debian/Ubuntu
534        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
535
536        echoAndLog "${FUNCNAME}(): dependencies installed"
537}
538
539# Hace un backup del fichero pasado por parámetro
540# deja un -last y uno para el día
541function backupFile()
542{
543        if [ $# -ne 1 ]; then
544                errorAndLog "${FUNCNAME}(): invalid number of parameters"
545                exit 1
546        fi
547
548        local file="$1"
549        local dateymd=`date +%Y%m%d`
550
551        if [ ! -f "$file" ]; then
552                warningAndLog "${FUNCNAME}(): file $file doesn't exists"
553                return 1
554        fi
555
556        echoAndLog "${FUNCNAME}(): making $file backup"
557
558        # realiza una copia de la última configuración como last
559        cp -a "$file" "${file}-LAST"
560
561        # si para el día no hay backup lo hace, sino no
562        if [ ! -f "${file}-${dateymd}" ]; then
563                cp -a "$file" "${file}-${dateymd}"
564        fi
565
566        echoAndLog "${FUNCNAME}(): $file backup success"
567}
568
569#####################################################################
570####### Funciones para el manejo de bases de datos
571#####################################################################
572
573# This function set password to root
574function mysqlSetRootPassword()
575{
576        if [ $# -ne 1 ]; then
577                errorAndLog "${FUNCNAME}(): invalid number of parameters"
578                exit 1
579        fi
580
581        local root_mysql="$1"
582        echoAndLog "${FUNCNAME}(): setting root password in MySQL server"
583        mysqladmin -u root password "$root_mysql"
584        if [ $? -ne 0 ]; then
585                errorAndLog "${FUNCNAME}(): error while setting root password in MySQL server"
586                return 1
587        fi
588        echoAndLog "${FUNCNAME}(): root password saved!"
589        return 0
590}
591
592# Si el servicio mysql esta ya instalado cambia la variable de la clave del root por la ya existente
593function mysqlGetRootPassword()
594{
595        local pass_mysql
596        local pass_mysql2
597        # Comprobar si MySQL está instalado con la clave de root por defecto.
598        if mysql -u root -p"$MYSQL_ROOT_PASSWORD" <<<"quit" 2>/dev/null; then
599                echoAndLog "${FUNCNAME}(): Using default mysql root password."
600        else
601                stty -echo
602                echo "There is a MySQL service already installed."
603                read -p "Enter MySQL root password: " pass_mysql
604                echo ""
605                read -p "Confrim password:" pass_mysql2
606                echo ""
607                stty echo
608                if [ "$pass_mysql" == "$pass_mysql2" ] ;then
609                        MYSQL_ROOT_PASSWORD="$pass_mysql"
610                        return 0
611                else
612                        echo "The keys don't match. Do not configure the server's key,"
613                        echo "transactions in the database will give error."
614                        return 1
615                fi
616        fi
617}
618
619# comprueba si puede conectar con mysql con el usuario root
620function mysqlTestConnection()
621{
622        if [ $# -ne 1 ]; then
623                errorAndLog "${FUNCNAME}(): invalid number of parameters"
624                exit 1
625        fi
626
627        local root_password="$1"
628        echoAndLog "${FUNCNAME}(): checking connection to mysql..."
629        # Componer fichero con credenciales de conexión a MySQL.
630        touch $TMPMYCNF
631        chmod 600 $TMPMYCNF
632        cat << EOT > $TMPMYCNF
633[client]
634user=root
635password=$root_password
636EOT
637        # Borrar el fichero temporal si termina el proceso de instalación.
638        trap "rm -f $TMPMYCNF" 0 1 2 3 6 9 15
639        # Comprobar conexión a MySQL.
640        echo "" | mysql --defaults-extra-file=$TMPMYCNF
641        if [ $? -ne 0 ]; then
642                errorAndLog "${FUNCNAME}(): connection to mysql failed, check root password and if daemon is running!"
643                return 1
644        else
645                echoAndLog "${FUNCNAME}(): connection success"
646                return 0
647        fi
648}
649
650# comprueba si la base de datos existe
651function mysqlDbExists()
652{
653        if [ $# -ne 1 ]; then
654                errorAndLog "${FUNCNAME}(): invalid number of parameters"
655                exit 1
656        fi
657
658        local database="$1"
659        echoAndLog "${FUNCNAME}(): checking if $database exists..."
660        echo "show databases" | mysql --defaults-extra-file=$TMPMYCNF | grep "^${database}$"
661        if [ $? -ne 0 ]; then
662                echoAndLog "${FUNCNAME}():database $database doesn't exists"
663                return 1
664        else
665                echoAndLog "${FUNCNAME}():database $database exists"
666                return 0
667        fi
668}
669
670# Comprueba si la base de datos está vacía.
671function mysqlCheckDbIsEmpty()
672{
673        if [ $# -ne 1 ]; then
674                errorAndLog "${FUNCNAME}(): invalid number of parameters"
675                exit 1
676        fi
677
678        local database="$1"
679        echoAndLog "${FUNCNAME}(): checking if $database is empty..."
680        num_tablas=`echo "show tables" | mysql --defaults-extra-file=$TMPMYCNF "${database}" | wc -l`
681        if [ $? -ne 0 ]; then
682                errorAndLog "${FUNCNAME}(): error executing query, check database and root password"
683                exit 1
684        fi
685
686        if [ $num_tablas -eq 0 ]; then
687                echoAndLog "${FUNCNAME}():database $database is empty"
688                return 0
689        else
690                echoAndLog "${FUNCNAME}():database $database has tables"
691                return 1
692        fi
693
694}
695
696# Importa un fichero SQL en la base de datos.
697# Parámetros:
698# - 1: nombre de la BD.
699# - 2: fichero a importar.
700# Nota: el fichero SQL puede contener las siguientes palabras reservadas:
701# - SERVERIP: se sustituye por la dirección IP del servidor.
702# - DBUSER: se sustituye por usuario de conexión a la BD definido en este script.
703# - DBPASSWD: se sustituye por la clave de conexión a la BD definida en este script.
704function mysqlImportSqlFileToDb()
705{
706        if [ $# -ne 2 ]; then
707                errorAndLog "${FNCNAME}(): invalid number of parameters"
708                exit 1
709        fi
710
711        local database="$1"
712        local sqlfile="$2"
713        local tmpfile=$(mktemp)
714        local i=0
715        local dev=""
716        local status
717
718        if [ ! -f $sqlfile ]; then
719                errorAndLog "${FUNCNAME}(): Unable to locate $sqlfile!!"
720                return 1
721        fi
722
723        echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..."
724        chmod 600 $tmpfile
725        for dev in ${DEVICE[*]}; do
726                if [ "${DEVICE[i]}" == "$DEFAULTDEV" ]; then
727                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
728                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
729                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
730                                $sqlfile > $tmpfile
731                fi
732                let i++
733        done
734        mysql --defaults-extra-file=$TMPMYCNF --default-character-set=utf8 "${database}" < $tmpfile
735        status=$?
736        rm -f $tmpfile
737        if [ $status -ne 0 ]; then
738                errorAndLog "${FUNCNAME}(): error while importing $sqlfile in database $database"
739                return 1
740        fi
741        echoAndLog "${FUNCNAME}(): file imported to database $database"
742        return 0
743}
744
745# Crea la base de datos
746function mysqlCreateDb()
747{
748        if [ $# -ne 1 ]; then
749                errorAndLog "${FUNCNAME}(): invalid number of parameters"
750                exit 1
751        fi
752
753        local database="$1"
754
755        echoAndLog "${FUNCNAME}(): creating database..."
756        mysqladmin --defaults-extra-file=$TMPMYCNF create $database
757        if [ $? -ne 0 ]; then
758                errorAndLog "${FUNCNAME}(): error while creating database $database"
759                return 1
760        fi
761        # Quitar modo ONLY_FULL_GROUP_BY de MySQL (ticket #730).
762        mysql --defaults-extra-file=$TMPMYCNF -e "SET GLOBAL sql_mode=(SELECT TRIM(BOTH ',' FROM REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')));"
763
764        echoAndLog "${FUNCNAME}(): database $database created"
765        return 0
766}
767
768# Comprueba si ya está definido el usuario de acceso a la BD.
769function mysqlCheckUserExists()
770{
771        if [ $# -ne 1 ]; then
772                errorAndLog "${FUNCNAME}(): invalid number of parameters"
773                exit 1
774        fi
775
776        local userdb="$1"
777
778        echoAndLog "${FUNCNAME}(): checking if $userdb exists..."
779        echo "select user from user where user='${userdb}'\\G" |mysql --defaults-extra-file=$TMPMYCNF mysql | grep user
780        if [ $? -ne 0 ]; then
781                echoAndLog "${FUNCNAME}(): user doesn't exists"
782                return 1
783        else
784                echoAndLog "${FUNCNAME}(): user already exists"
785                return 0
786        fi
787
788}
789
790# Crea un usuario administrativo para la base de datos
791function mysqlCreateAdminUserToDb()
792{
793        if [ $# -ne 3 ]; then
794                errorAndLog "${FUNCNAME}(): invalid number of parameters"
795                exit 1
796        fi
797
798        local database="$1"
799        local userdb="$2"
800        local passdb="$3"
801
802        echoAndLog "${FUNCNAME}(): creating admin user ${userdb} to database ${database}"
803
804        cat > $WORKDIR/create_${database}.sql <<EOF
805CREATE USER '${userdb}'@'localhost' IDENTIFIED BY '${passdb}';
806GRANT USAGE ON *.* TO '${userdb}'@'localhost';
807GRANT ALL PRIVILEGES ON ${database}.* TO '${userdb}'@'localhost' WITH GRANT OPTION;
808FLUSH PRIVILEGES;
809EOF
810        mysql --defaults-extra-file=$TMPMYCNF < $WORKDIR/create_${database}.sql
811        if [ $? -ne 0 ]; then
812                errorAndLog "${FUNCNAME}(): error while creating user in mysql"
813                rm -f $WORKDIR/create_${database}.sql
814                return 1
815        else
816                echoAndLog "${FUNCNAME}(): user created ok"
817                rm -f $WORKDIR/create_${database}.sql
818                return 0
819        fi
820}
821
822
823#####################################################################
824####### Funciones para la descarga de código
825#####################################################################
826
827# Obtiene el código fuente del proyecto desde el repositorio de GitHub.
828function downloadCode()
829{
830        if [ $# -ne 1 ]; then
831                errorAndLog "${FUNCNAME}(): invalid number of parameters"
832                exit 1
833        fi
834
835        local url="$1"
836
837        echoAndLog "${FUNCNAME}(): downloading code from '$url'..."
838
839        GIT_SSH_COMMAND="ssh -o StrictHostKeyChecking=accept-new" git archive --remote=$url --format zip --output opengnsys.zip --prefix=opengnsys/ $BRANCH && unzip opengnsys.zip
840        if [ $? -ne 0 ]; then
841                errorAndLog "${FUNCNAME}(): error getting OpenGnsys code from $url"
842                return 1
843        fi
844        rm -f opengnsys.zip
845        echoAndLog "${FUNCNAME}(): code was downloaded"
846        return 0
847}
848
849
850############################################################
851###  Detectar red
852############################################################
853
854# Comprobar si existe conexión.
855function checkNetworkConnection()
856{
857        set -x
858        echoAndLog "${FUNCNAME}(): Checking OpenGnsys server connectivity."
859        OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"opengnsys.es"}
860        if which curl &>/dev/null; then
861                curl --connect-timeout 10 --retry 5 --retry-delay 5 --max-time 30 "https://$OPENGNSYS_SERVER/" -o /dev/null && \
862                        curl --connect-timeout 10 --retry 5 --retry-delay 5 --max-time 30 "http://$OPENGNSYS_SERVER/" -o /dev/null
863        elif which wget &>/dev/null; then
864                wget --spider -q "https://$OPENGNSYS_SERVER/" && \
865                        wget --spider -q "http://$OPENGNSYS_SERVER/"
866        else
867                echoAndLog "${FUNCNAME}(): Cannot execute \"wget\" nor \"curl\"."
868                return 1
869        fi
870        set +x
871}
872
873# Convierte nº de bits (notación CIDR) en máscara de red (gracias a FriedZombie en openwrt.org).
874cidr2mask ()
875{
876        # Number of args to shift, 255..255, first non-255 byte, zeroes
877        set -- $[ 5 - ($1 / 8) ] 255 255 255 255 $[ (255 << (8 - ($1 % 8))) & 255 ] 0 0 0
878        [ $1 -gt 1 ] && shift $1 || shift
879        echo ${1-0}.${2-0}.${3-0}.${4-0}
880}
881
882# Obtener los parámetros de red de la interfaz por defecto.
883function getNetworkSettings()
884{
885        # Arrays globales definidas:
886        # - DEVICE:     nombres de dispositivos de red activos.
887        # - SERVERIP:   IPs locales del servidor.
888        # - NETIP:      IPs de redes.
889        # - NETMASK:    máscaras de red.
890        # - NETBROAD:   IPs de difusión de redes.
891        # - ROUTERIP:   IPs de routers.
892        # Otras variables globales:
893        # - DEFAULTDEV: dispositivo de red por defecto.
894        # - DNSIP:      IP del servidor DNS principal.
895
896        local i=0
897        local dev=""
898
899        echoAndLog "${FUNCNAME}(): Detecting network parameters."
900        DEVICE=( $(ip -o link show up | awk '!/loopback/ {sub(/[:@].*/,"",$2); print $2}') )
901        if [ -z "$DEVICE" ]; then
902                errorAndLog "${FUNCNAME}(): Network devices not detected."
903                exit 1
904        fi
905        for dev in ${DEVICE[*]}; do
906                SERVERIP[i]=$(ip -o addr show dev "$dev" | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4); exit;}')
907                if [ -n "${SERVERIP[i]}" ]; then
908                        NETMASK[i]=$( cidr2mask $(ip -o addr show dev "$dev" | awk '$3~/inet$/ {sub (/.*\//, "", $4); print ($4); exit;}') )
909                        NETBROAD[i]=$(ip -o addr show dev "$dev" | awk '$3~/inet$/ {print ($6); exit;}')
910                        NETIP[i]=$(ip route list proto kernel | awk -v d="$dev" '$3==d && /src/ {sub (/\/.*/,""); print $1; exit;}')
911                        ROUTERIP[i]=$(ip route list default | awk -v d="$dev" '$5==d {print $3; exit;}')
912                        if [ $DHCPNET == ${NETIP[i]} ]; then
913                                DEFAULTDEV="$dev"
914                        else
915                                DEFAULTDEV=${DEFAULTDEV:-"$dev"}
916                        fi
917                fi
918                let i++
919        done
920        DNSIP=$(systemd-resolve --status 2>/dev/null | awk '/DNS Servers:/ {print $3; exit;}')
921        [ -z "$DNSIP" ] && DNSIP=$(awk '/nameserver/ {print $2; exit;}' /etc/resolv.conf)
922        if [ -z "${NETIP[*]}" -o -z "${NETMASK[*]}" ]; then
923                errorAndLog "${FUNCNAME}(): Network not detected."
924                exit 1
925        fi
926
927        # Variables de ejecución de Apache
928        # - APACHE_RUN_USER
929        # - APACHE_RUN_GROUP
930        if [ -f $APACHECFGDIR/envvars ]; then
931                source $APACHECFGDIR/envvars
932        fi
933        APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
934        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
935
936        echoAndLog "${FUNCNAME}(): Default network device: $DEFAULTDEV."
937}
938
939
940############################################################
941### Esqueleto para el Servicio pxe y contenedor tftpboot ###
942############################################################
943
944function tftpConfigure()
945{
946        echoAndLog "${FUNCNAME}(): Configuring TFTP service."
947        # Habilitar TFTP y reiniciar Inetd.
948        if [ -n "$TFTPSERV" ]; then
949                if [ -f $INETDCFGDIR/$TFTPSERV ]; then
950                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/$TFTPSERV
951                else
952                        service=$TFTPSERV
953                        $ENABLESERVICE; $STARTSERVICE
954                fi
955        fi
956        service=$INETDSERV
957        $ENABLESERVICE; $STARTSERVICE
958
959        # comprobamos el servicio tftp
960        sleep 1
961        testPxe
962}
963
964# Comprueba que haya conexión al servicio TFTP/PXE.
965function testPxe ()
966{
967        echoAndLog "${FUNCNAME}(): Checking TFTP service... please wait."
968        echo "test" >$TFTPCFGDIR/testpxe
969        tftp -v 127.0.0.1 -c get testpxe /tmp/testpxe && echoAndLog "TFTP service is OK." || errorAndLog "TFTP service is down."
970        rm -f $TFTPCFGDIR/testpxe /tmp/testpxe
971}
972
973
974########################################################################
975## Configuración servicio Samba
976########################################################################
977
978# Configurar servicios Samba.
979function smbConfigure()
980{
981        echoAndLog "${FUNCNAME}(): Configuring Samba service."
982
983        backupFile $SAMBACFGDIR/smb.conf
984
985        # Copiar plantailla de recursos para OpenGnsys
986        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
987                $WORKDIR/opengnsys/server/etc/smb-og.conf.tmpl > $SAMBACFGDIR/smb-og.conf
988        # Configurar y recargar Samba"
989        perl -pi -e "s/WORKGROUP/OPENGNSYS/; s/server string \=.*/server string \= OpenGnsys Samba Server/" $SAMBACFGDIR/smb.conf
990        if ! grep -q "smb-og" $SAMBACFGDIR/smb.conf; then
991                echo "include = $SAMBACFGDIR/smb-og.conf" >> $SAMBACFGDIR/smb.conf
992        fi
993        service=$SAMBASERV
994        $ENABLESERVICE; $STARTSERVICE
995        if [ $? -ne 0 ]; then
996                errorAndLog "${FUNCNAME}(): error while configure Samba"
997                return 1
998        fi
999        # Crear clave para usuario de acceso a los recursos.
1000        echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | smbpasswd -a -s $OPENGNSYS_CLIENT_USER
1001
1002        echoAndLog "${FUNCNAME}(): Added Samba configuration."
1003        return 0
1004}
1005
1006
1007########################################################################
1008## Configuración servicio Rsync
1009########################################################################
1010
1011# Configurar servicio Rsync.
1012function rsyncConfigure()
1013{
1014        echoAndLog "${FUNCNAME}(): Configuring Rsync service."
1015
1016        backupFile $RSYNCCFGDIR/rsyncd.conf
1017
1018        # Configurar acceso a Rsync.
1019        sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENT_USER/g" \
1020                $WORKDIR/opengnsys/repoman/etc/rsyncd.conf.tmpl > $RSYNCCFGDIR/rsyncd.conf
1021        # Habilitar Rsync y reiniciar Inetd.
1022        if [ -n "$RSYNCSERV" ]; then
1023                if [ -f /etc/default/rsync ]; then
1024                        perl -pi -e 's/RSYNC_ENABLE=.*/RSYNC_ENABLE=inetd/' /etc/default/rsync
1025                fi
1026                if [ -f $INETDCFGDIR/rsync ]; then
1027                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/rsync
1028                else
1029                        cat << EOT > $INETDCFGDIR/rsync
1030service rsync
1031{
1032        disable = no
1033        socket_type = stream
1034        wait = no
1035        user = root
1036        server = $(which rsync)
1037        server_args = --daemon
1038        log_on_failure += USERID
1039        flags = IPv6
1040}
1041EOT
1042                fi
1043                service=$RSYNCSERV $ENABLESERVICE
1044                service=$INETDSERV $STARTSERVICE
1045        fi
1046
1047        echoAndLog "${FUNCNAME}(): Added Rsync configuration."
1048        return 0
1049}
1050
1051
1052########################################################################
1053## Configuración servicio DHCP
1054########################################################################
1055
1056# Configurar servicios DHCP.
1057function dhcpConfigure()
1058{
1059        echoAndLog "${FUNCNAME}(): Sample DHCP configuration."
1060
1061        local errcode=0
1062        local i=0
1063        local dev=""
1064
1065        backupFile $DHCPCFGDIR/dhcpd.conf
1066        for dev in ${DEVICE[*]}; do
1067                if [ -n "${SERVERIP[i]}" ]; then
1068                        backupFile $DHCPCFGDIR/dhcpd-$dev.conf
1069                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1070                            -e "s/NETIP/${NETIP[i]}/g" \
1071                            -e "s/NETMASK/${NETMASK[i]}/g" \
1072                            -e "s/NETBROAD/${NETBROAD[i]}/g" \
1073                            -e "s/ROUTERIP/${ROUTERIP[i]}/g" \
1074                            -e "s/DNSIP/$DNSIP/g" \
1075                            $WORKDIR/opengnsys/server/etc/dhcpd.conf.tmpl > $DHCPCFGDIR/dhcpd-$dev.conf || errcode=1
1076                fi
1077                let i++
1078        done
1079        if [ $errcode -ne 0 ]; then
1080                errorAndLog "${FUNCNAME}(): error while configuring DHCP server"
1081                return 1
1082        fi
1083        ln -f $DHCPCFGDIR/dhcpd-$DEFAULTDEV.conf $DHCPCFGDIR/dhcpd.conf
1084        service=$DHCPSERV
1085        $ENABLESERVICE; $STARTSERVICE
1086        echoAndLog "${FUNCNAME}(): Sample DHCP configured in \"$DHCPCFGDIR\"."
1087        return 0
1088}
1089
1090
1091#####################################################################
1092####### Funciones específicas de la instalación de Opengnsys
1093#####################################################################
1094
1095# Copiar ficheros del OpenGnsys Web Console.
1096function installWebFiles()
1097{
1098        local COMPATDIR f
1099        local SLIMFILE="slim-2.6.1.zip"
1100        local SWAGGERFILE="swagger-ui-2.2.5.zip"
1101
1102        echoAndLog "${FUNCNAME}(): Installing web files..."
1103        # Copiar ficheros.
1104        cp -a $WORKDIR/opengnsys/admin/WebConsole/* $INSTALL_TARGET/www   #*/ comentario para Doxygen.
1105        if [ $? != 0 ]; then
1106                errorAndLog "${FUNCNAME}(): Error copying web files."
1107                exit 1
1108        fi
1109
1110        # Descomprimir librerías: Slim y Swagger-UI.
1111        unzip -o $WORKDIR/opengnsys/admin/$SLIMFILE -d $INSTALL_TARGET/www/rest
1112        unzip -o $WORKDIR/opengnsys/admin/$SWAGGERFILE -d $INSTALL_TARGET/www/rest
1113
1114        # Compatibilidad con dispositivos móviles.
1115        COMPATDIR="$INSTALL_TARGET/www/principal"
1116        for f in acciones administracion aula aulas hardwares imagenes menus repositorios softwares; do
1117                sed 's/clickcontextualnodo/clicksupnodo/g' $COMPATDIR/$f.php > $COMPATDIR/$f.device.php
1118        done
1119        cp -a $COMPATDIR/imagenes.device.php $COMPATDIR/imagenes.device4.php
1120        # Acceso al manual de usuario
1121        ln -fs ../doc/userManual $INSTALL_TARGET/www/userManual
1122        # Ficheros de log de la API REST.
1123        touch $INSTALL_TARGET/log/{ogagent,remotepc,rest}.log
1124
1125        echoAndLog "${FUNCNAME}(): Web files installed successfully."
1126}
1127
1128function configurePHPvars()
1129{
1130    OGADMSRV_HOSTNAME=$1
1131    OGADMSRV_PORT=$2
1132    sed "s/__OGADMSRV_HOSTNAME__/$OGADMSRV_HOSTNAME/; s/__OGADMSRV_PORT__/$OGADMSRV_PORT/" <$WORKDIR/opengnsys/server/etc/php-vars.php.tmpl >$INSTALL_TARGET/etc/php-vars.php
1133}
1134
1135# Copiar ficheros en la zona de descargas de OpenGnsys Web Console.
1136function installDownloadableFiles()
1137{
1138        local VERSIONFILE OGVERSION FILENAME TARGETFILE
1139
1140        # Obtener versión a descargar.
1141        VERSIONFILE="$INSTALL_TARGET/doc/VERSION.json"
1142        OGVERSION="$(jq -r ".ogagent // \"$INSTVERSION\"" $VERSIONFILE 2>/dev/null || echo "$INSTVERSION")"
1143        FILENAME="ogagentpkgs-$OGVERSION.tar.gz"
1144        TARGETFILE=$WORKDIR/$FILENAME
1145
1146        # Descargar archivo comprimido, si es necesario.
1147        if [ -s $PROGRAMDIR/$FILENAME ]; then
1148                echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
1149                mv $PROGRAMDIR/$FILENAME $TARGETFILE
1150        else
1151                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
1152                curl --retry 5 --retry-delay 5 --max-time 30 $DOWNLOADURL/$FILENAME -o $TARGETFILE
1153        fi
1154        if [ ! -s $TARGETFILE ]; then
1155                errorAndLog "${FUNCNAME}(): Cannot download $FILENAME"
1156                return 1
1157        fi
1158
1159        # Descomprimir fichero en zona de descargas.
1160        tar xvzf $TARGETFILE -C $INSTALL_TARGET/www/descargas
1161        if [ $? != 0 ]; then
1162                errorAndLog "${FUNCNAME}(): Error uncompressing archive."
1163                exit 1
1164        fi
1165}
1166
1167# Configuración específica de Apache.
1168function installWebConsoleApacheConf()
1169{
1170        if [ $# -ne 2 ]; then
1171                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1172                exit 1
1173        fi
1174
1175        local path_opengnsys_base="$1"
1176        local path_apache2_confd="$2"
1177        local CONSOLEDIR=${path_opengnsys_base}/www
1178        local sockfile
1179
1180        if [ ! -d $path_apache2_confd ]; then
1181                errorAndLog "${FUNCNAME}(): path to apache2 conf.d can not found, verify your server installation"
1182                return 1
1183        fi
1184
1185        mkdir -p $path_apache2_confd/{sites-available,sites-enabled}
1186
1187        echoAndLog "${FUNCNAME}(): creating apache2 config file.."
1188
1189        # Avtivar PHP-FPM.
1190        echoAndLog "${FUNCNAME}(): configuring PHP-FPM"
1191        service=$PHPFPMSERV
1192        $ENABLESERVICE; $STARTSERVICE
1193        sockfile=$(find /run/php -name "php*.sock" -type s -print 2>/dev/null | tail -1)
1194
1195        # Activar módulos de Apache.
1196        $APACHEENABLEMODS
1197        # Activar HTTPS.
1198        $APACHEENABLESSL
1199        $APACHEMAKECERT
1200        # Genera configuración de consola web a partir del fichero plantilla.
1201        if [ -n "$(apachectl -v | grep "2\.[0-2]")" ]; then
1202                # Configuración para versiones anteriores de Apache.
1203                sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
1204                        $WORKDIR/opengnsys/server/etc/apache-prev2.4.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}
1205        else
1206                # Configuración específica a partir de Apache 2.4
1207                if [ -n "$sockfile" ]; then
1208                        sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
1209                            -e "s,proxy:fcgi:.*,proxy:unix:${sockfile%% *}|fcgi://localhost\",g" \
1210                                $WORKDIR/opengnsys/server/etc/apache.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf
1211                else
1212                        sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
1213                                $WORKDIR/opengnsys/server/etc/apache.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf
1214                fi
1215        fi
1216        $APACHEENABLEOG
1217        if [ $? -ne 0 ]; then
1218                errorAndLog "${FUNCNAME}(): config file can't be linked to apache conf, verify your server installation"
1219                return 1
1220        fi
1221        echoAndLog "${FUNCNAME}(): config file created and linked, restarting apache daemon"
1222        service=$APACHESERV
1223        $ENABLESERVICE; $STARTSERVICE
1224        return 0
1225}
1226
1227
1228# Crear documentación Doxygen para la consola web.
1229function makeDoxygenFiles()
1230{
1231        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
1232        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
1233                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
1234        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
1235                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
1236                return 1
1237        fi
1238        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
1239        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
1240}
1241
1242
1243# Crea la estructura base de la instalación de opengnsys
1244function createDirs()
1245{
1246        if [ $# -ne 1 ]; then
1247                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1248                exit 1
1249        fi
1250
1251        local path_opengnsys_base="$1"
1252
1253        # Crear estructura de directorios.
1254        echoAndLog "${FUNCNAME}(): creating directory paths in $path_opengnsys_base"
1255        mkdir -p $path_opengnsys_base
1256        mkdir -p $path_opengnsys_base/bin
1257        mkdir -p $path_opengnsys_base/client/{cache,images,log}
1258        mkdir -p $path_opengnsys_base/doc
1259        mkdir -p $path_opengnsys_base/etc
1260        mkdir -p $path_opengnsys_base/lib
1261        mkdir -p $path_opengnsys_base/log/clients
1262        ln -fs $path_opengnsys_base/log /var/log/opengnsys
1263        mkdir -p $path_opengnsys_base/sbin
1264        mkdir -p $path_opengnsys_base/www
1265        mkdir -p $path_opengnsys_base/images/groups
1266        mkdir -p $TFTPCFGDIR
1267        ln -fs $TFTPCFGDIR $path_opengnsys_base/tftpboot
1268        mkdir -p $path_opengnsys_base/tftpboot/{menu.lst,grub}
1269        if [ $? -ne 0 ]; then
1270                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
1271                return 1
1272        fi
1273
1274        # Crear usuario ficticio.
1275        if id -u $OPENGNSYS_CLIENT_USER &>/dev/null; then
1276                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENT_USER\" is already created"
1277        else
1278                echoAndLog "${FUNCNAME}(): creating OpenGnsys user"
1279                useradd $OPENGNSYS_CLIENT_USER 2>/dev/null
1280                if [ $? -ne 0 ]; then
1281                        errorAndLog "${FUNCNAME}(): error creating OpenGnsys user"
1282                        return 1
1283                fi
1284        fi
1285
1286        # Mover el fichero de registro de instalación al directorio de logs.
1287        echoAndLog "${FUNCNAME}(): moving installation log file"
1288        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
1289        chmod 600 $LOG_FILE
1290
1291        echoAndLog "${FUNCNAME}(): directory paths created"
1292        return 0
1293}
1294
1295# Copia ficheros de configuración y ejecutables genéricos del servidor.
1296function copyServerFiles ()
1297{
1298        if [ $# -ne 1 ]; then
1299                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1300                exit 1
1301        fi
1302
1303        local path_opengnsys_base="$1"
1304
1305        # Lista de ficheros y directorios origen y de directorios destino.
1306        local SOURCES=( server/tftpboot \
1307                        /usr/lib/shim/shimx64.efi.signed \
1308                        /usr/lib/grub/x86_64-efi-signed/grubnetx64.efi.signed \
1309                        server/bin \
1310                        repoman/bin \
1311                        server/lib \
1312                        admin/Sources/Services/ogAdmServerAux
1313                        admin/Sources/Services/ogAdmRepoAux
1314                        installer/opengnsys_uninstall.sh \
1315                        installer/opengnsys_update.sh \
1316                        installer/opengnsys_export.sh \
1317                        installer/opengnsys_import.sh \
1318                        doc )
1319        local TARGETS=( tftpboot \
1320                        tftpboot \
1321                        tftpboot/grubx64.efi \
1322                        bin \
1323                        bin \
1324                        lib \
1325                        sbin \
1326                        sbin \
1327                        lib \
1328                        lib \
1329                        lib \
1330                        lib \
1331                        doc )
1332
1333        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
1334                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
1335                exit 1
1336        fi
1337
1338        # Copiar ficheros.
1339        echoAndLog "${FUNCNAME}(): copying files to server directories"
1340
1341        pushd $WORKDIR/opengnsys
1342        local i
1343        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
1344                if [ -f "${SOURCES[$i]}" ]; then
1345                        echoAndLog "Copying ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1346                        cp -a "${SOURCES[$i]}" "${path_opengnsys_base}/${TARGETS[$i]}"
1347                elif [ -d "${SOURCES[$i]}" ]; then
1348                        echoAndLog "Copying content of ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1349                        cp -a "${SOURCES[$i]}"/* "${path_opengnsys_base}/${TARGETS[$i]}"
1350                else
1351                        warningAndLog "Unable to copy ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1352                fi
1353        done
1354
1355        popd
1356}
1357
1358####################################################################
1359### Funciones de TLS
1360####################################################################
1361
1362CA_DIR=/root/CA
1363OG_BASEDIR=/opt/opengnsys
1364
1365function gatherCertsInfo()
1366{
1367    ERRORS=0
1368    ## BUG cuando REMOTE=1, $WORKDIR/opengnsys es el contenido del zip (producido al vuelo con 'git archive'), y naturalmente no contiene ./user-certs
1369    ##     este código debe buscar los certificados en otro sitio adicional
1370    if [ -f $WORKDIR/opengnsys/user-certs/ca.crt.pem ]; then
1371        echoAndLog "CA provided by the user, checking presence of all certificates"
1372
1373        TLS_DATA_CA_CERTFILE=$WORKDIR/opengnsys/user-certs/ca.crt.pem
1374        TLS_DATA_OGADMSRV_CERTFILE=$WORKDIR/opengnsys/user-certs/ogAdmSrv.crt.pem
1375        TLS_DATA_OGADMSRV_KEYFILE=$WORKDIR/opengnsys/user-certs/ogAdmSrv.key.pem
1376        TLS_DATA_WEBCONSOLE_CERTFILE=$WORKDIR/opengnsys/user-certs/WebConsole.crt.pem
1377        TLS_DATA_WEBCONSOLE_KEYFILE=$WORKDIR/opengnsys/user-certs/WebConsole.key.pem
1378
1379        ## el usuario tiene que facilitar todos los certificados
1380        ## si falta alguno, no podemos generarlo aquí porque habría que tener la privkey de la CA, y el usuario no nos la debe dar
1381        if [ ! -f $TLS_DATA_OGADMSRV_CERTFILE   ]; then errorAndLog "ogAdmSrv certificate not found";   ERRORS=1; fi
1382        if [ ! -f $TLS_DATA_OGADMSRV_KEYFILE    ]; then errorAndLog "ogAdmSrv privkey not found";       ERRORS=1; fi
1383        if [ ! -f $TLS_DATA_WEBCONSOLE_CERTFILE ]; then errorAndLog "WebConsole certificate not found"; ERRORS=1; fi
1384        if [ ! -f $TLS_DATA_WEBCONSOLE_KEYFILE  ]; then errorAndLog "WebConsole privkey not found";     ERRORS=1; fi
1385
1386        if [ $ERRORS -eq 0 ]; then
1387            ## validar que las privkeys no tengan contraseña para que opengnsys pueda arrancar de forma desatendida
1388            if ! openssl rsa -in $TLS_DATA_OGADMSRV_KEYFILE   -passin pass:42 -noout; then errorAndLog "ogAdmSrv privkey is encrypted";   ERRORS=1; fi
1389            if ! openssl rsa -in $TLS_DATA_WEBCONSOLE_KEYFILE -passin pass:42 -noout; then errorAndLog "WebConsole privkey is encrypted"; ERRORS=1; fi
1390
1391            if [ $ERRORS -eq 0 ]; then
1392                # obtener los subject de cada certificado
1393                # la salida de openssl es tal que "subject=C = ES, ST = Madrid, L = Madrid, CN = test.example.org"
1394                # con el sed cocinamos la salida
1395                # además añadimos un / al principio para que el CN final sea correcto: "/C=ES/ST=Madrid/L=Madrid/CN=test.opengnsys.local"
1396                TLS_DATA_CA_SUBJ=/$(        openssl x509 -in $TLS_DATA_CA_CERTFILE         -subject -noout |sed 's/^subject=//; s/ *//g; s/,/\//g')
1397                TLS_DATA_OGADMSRV_SUBJ=/$(  openssl x509 -in $TLS_DATA_OGADMSRV_CERTFILE   -subject -noout |sed 's/^subject=//; s/ *//g; s/,/\//g')
1398                TLS_DATA_WEBCONSOLE_SUBJ=/$(openssl x509 -in $TLS_DATA_WEBCONSOLE_CERTFILE -subject -noout |sed 's/^subject=//; s/ *//g; s/,/\//g')
1399
1400                # obtener CN a partir del subject
1401                TLS_DATA_CA_CN=$(         echo $TLS_DATA_CA_SUBJ         |sed 's/.*CN=\([^/$]*\).*/\1/')
1402                TLS_DATA_OGADMSRV_CN=$(   echo $TLS_DATA_OGADMSRV_SUBJ   |sed 's/.*CN=\([^/$]*\).*/\1/')
1403                TLS_DATA_WEBCONSOLE_CN=$( echo $TLS_DATA_WEBCONSOLE_SUBJ |sed 's/.*CN=\([^/$]*\).*/\1/')
1404
1405                # los CN de los componentes que aceptan conexiones deberían resolver a una IP
1406                if ! nslookup $TLS_DATA_OGADMSRV_CN &>/dev/null; then errorAndLog "ogAdmSrv CN doesn't resolve to an IP"; ERRORS=1; fi
1407
1408                if [ $ERRORS -eq 0 ]; then
1409                    echoAndLog "Provided CA and certs are ok"
1410                fi
1411            fi
1412        fi
1413    fi
1414
1415    ## aquí también hay que tener en cuenta el sitio adicional para los user-certs
1416    if [ ! -f $WORKDIR/opengnsys/user-certs/ca.crt.pem -o $ERRORS -eq 1 ]; then
1417        echoAndLog "CA and certs not provided by the user or issues found, we will generate a new CA and all certs"
1418
1419        TLS_DATA_CA_CN=ca.opengnsys.local
1420        TLS_DATA_CA_SUBJ=/CN=ca.opengnsys.local
1421        TLS_DATA_CA_CERTFILE=$CA_DIR/certs/ca.crt.pem
1422        TLS_DATA_CA_EXPIRY=7300           # this variable is used later to make some decisions
1423
1424        TLS_DATA_OGADMSRV_CN=ogAdmSrv.opengnsys.local
1425        TLS_DATA_OGADMSRV_SUBJ=/CN=ogAdmSrv.opengnsys.local
1426        TLS_DATA_OGADMSRV_CERTFILE=$CA_DIR/certs/ogAdmSrv.crt.pem
1427        TLS_DATA_OGADMSRV_KEYFILE=$CA_DIR/private/ogAdmSrv.key.pem
1428        TLS_DATA_OGADMSRV_EXPIRY=375
1429
1430        TLS_DATA_WEBCONSOLE_CN=WebConsole.opengnsys.local
1431        TLS_DATA_WEBCONSOLE_SUBJ=/CN=WebConsole.opengnsys.local
1432        TLS_DATA_WEBCONSOLE_CERTFILE=$CA_DIR/certs/WebConsole.crt.pem
1433        TLS_DATA_WEBCONSOLE_KEYFILE=$CA_DIR/private/WebConsole.key.pem
1434        TLS_DATA_WEBCONSOLE_EXPIRY=375
1435    fi
1436
1437    # otras cosas de TLS no cubiertas arriba por no estar relacionadas con los certificados
1438    TLS_DATA_OGADMSRV_LISTEN_PORT=48888
1439
1440    return 0
1441}
1442
1443function _genCA ()
1444{
1445    SUBJ=$1
1446    EXPIRY_DAYS=$2
1447    openssl genrsa -out private/ca.key.pem 4096
1448    openssl req -config openssl.cnf -key private/ca.key.pem -new -x509 -days $EXPIRY_DAYS -sha256 -subj $SUBJ -out certs/ca.crt.pem
1449
1450    return 0
1451}
1452
1453function _genCert ()
1454{
1455    COMPONENT=$1
1456    SUBJ=$2
1457    EXPIRY_DAYS=$3
1458
1459    openssl genrsa -out private/$COMPONENT.key.pem 2048
1460    openssl req -config openssl.cnf -key private/$COMPONENT.key.pem -new -sha256 -subj $SUBJ -out csr/$COMPONENT.csr.pem
1461    openssl ca -config openssl.cnf -batch -days $EXPIRY_DAYS -notext -md sha256 -in csr/$COMPONENT.csr.pem -out certs/$COMPONENT.crt.pem
1462
1463    return 0
1464}
1465
1466function genAllCerts ()
1467{
1468    mkdir -p $CA_DIR
1469    pushd $CA_DIR
1470    cat >openssl.cnf <<EOF
1471[ca]
1472default_ca = CA_default
1473
1474[CA_default]
1475dir                    = $CA_DIR
1476certs                  = $CA_DIR/certs
1477new_certs_dir          = $CA_DIR/newcerts
1478database               = $CA_DIR/index.txt
1479serial                 = $CA_DIR/serial
1480default_md             = sha256
1481policy                 = policy_loose
1482
1483private_key            = $CA_DIR/private/ca.key.pem
1484certificate            = $CA_DIR/certs/ca.crt.pem
1485
1486[policy_loose]
1487countryName            = optional
1488stateOrProvinceName    = optional
1489localityName           = optional
1490organizationName       = optional
1491organizationalUnitName = optional
1492commonName             = supplied
1493emailAddress           = optional
1494
1495[req]
1496default_bits           = 2048
1497distinguished_name     = req_distinguished_name
1498default_md             = sha256
1499
1500[req_distinguished_name]
1501countryName            = Country Name (2 letter code)
1502EOF
1503    mkdir certs csr newcerts private
1504    chmod 0700 private
1505    touch index.txt index.txt.attr
1506    echo 1000 >serial
1507
1508    _genCA              $TLS_DATA_CA_SUBJ         $TLS_DATA_CA_EXPIRY
1509    _genCert ogAdmSrv   $TLS_DATA_OGADMSRV_SUBJ   $TLS_DATA_OGADMSRV_EXPIRY
1510    _genCert WebConsole $TLS_DATA_WEBCONSOLE_SUBJ $TLS_DATA_WEBCONSOLE_EXPIRY
1511
1512    popd
1513    return 0
1514}
1515
1516function installAllCerts ()
1517{
1518    mkdir -p $OG_BASEDIR/etc/ssl
1519
1520    ## CA cert goes to the OS store
1521    cp $TLS_DATA_CA_CERTFILE $LOCAL_CERTS_DIR/opengnsys-ca.crt
1522
1523    ## ogAdmSrv cert & key go to the application store
1524    cp $TLS_DATA_OGADMSRV_CERTFILE $TLS_DATA_OGADMSRV_KEYFILE $OG_BASEDIR/etc/ssl/
1525    ## certs of ogAdmSrv clients go to the OS store (stunnel seems to require this)
1526    cp $TLS_DATA_WEBCONSOLE_CERTFILE $LOCAL_CERTS_DIR/opengnsys-WebConsole.crt
1527
1528    ## WebConsole cert & key go to the application store
1529    cp $TLS_DATA_WEBCONSOLE_CERTFILE $TLS_DATA_WEBCONSOLE_KEYFILE $OG_BASEDIR/etc/ssl/
1530
1531    $UPDATE_CA_CMD
1532    chgrp stunnel4 $OG_BASEDIR/etc/ssl/*
1533
1534    return 0
1535}
1536
1537# si generamos nuestros propios certificados, los CNs tienen que resolver a alguna IP
1538# no podemos dar por hecho que algún servidor DNS por ahí fuera resuelva los CNs que hemos generado al instalar
1539function makeCommonNamesResolvable ()
1540{
1541    # ogAdmSrv
1542        local i=0
1543        for dev in ${DEVICE[*]}; do
1544            echoAndLog "${FUNCNAME}(): evaluating dev (${DEVICE[i]}) against defaultdev ($DEFAULTDEV)"
1545                if [ "${DEVICE[i]}" == "$DEFAULTDEV" ]; then
1546            ETC_HOSTS_IP=${SERVERIP[i]}
1547                echoAndLog "${FUNCNAME}(): will use dev (${DEVICE[i]}) IP ($ETC_HOSTS_IP)"
1548            break
1549                fi
1550                let i++
1551        done
1552
1553    if [ -z $ETC_HOSTS_IP ]; then
1554            echoAndLog "${FUNCNAME}(): Don't know what IP address to add to /etc/hosts for ogAdmSrv"
1555    else
1556        echo "$ETC_HOSTS_IP  $TLS_DATA_OGADMSRV_CN" >>/etc/hosts
1557    fi
1558
1559    return 0
1560}
1561
1562function configureStunnel ()
1563{
1564        local i=0
1565        for dev in ${DEVICE[*]}; do
1566            echoAndLog "${FUNCNAME}(): evaluating dev (${DEVICE[i]}) against defaultdev ($DEFAULTDEV)"
1567                if [ "${DEVICE[i]}" == "$DEFAULTDEV" ]; then
1568            LISTEN_IP=${SERVERIP[i]}
1569                echoAndLog "${FUNCNAME}(): will use dev (${DEVICE[i]}) IP ($LISTEN_IP)"
1570            break
1571                fi
1572                let i++
1573        done
1574
1575    if [ -z $LISTEN_IP ]; then
1576            echoAndLog "${FUNCNAME}(): Don't know what IP address to listen on"
1577        return 1
1578    fi
1579
1580    cat >/etc/stunnel/ogAdmSrv.conf <<EOF
1581setuid = stunnel4
1582setgid = stunnel4
1583pid = /var/run/stunnel4/ogAdmSrv.pid
1584
1585[ogAdmSrv]
1586accept = $LISTEN_IP:$TLS_DATA_OGADMSRV_LISTEN_PORT
1587connect = 127.0.0.1:8888
1588cert = $OG_BASEDIR/etc/ssl/ogAdmSrv.crt.pem
1589key = $OG_BASEDIR/etc/ssl/ogAdmSrv.key.pem
1590capath = $STUNNEL_CAPATH
1591requireCert = yes
1592verifyPeer = yes
1593verifyChain = yes
1594EOF
1595
1596    sed -i -e '/^ENABLED=/s/0/1/' /etc/default/stunnel4
1597    service=stunnel4
1598    $STARTSERVICE
1599    return 0
1600}
1601
1602
1603####################################################################
1604### Funciones de compilación de código fuente de servicios
1605####################################################################
1606
1607# Compilar los servicios de OpenGnsys
1608function servicesCompilation ()
1609{
1610        local hayErrores=0
1611
1612        # Compilar OpenGnsys Server
1613        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Server"
1614        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
1615        make && mv ogAdmServer $INSTALL_TARGET/sbin
1616        if [ $? -ne 0 ]; then
1617                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Server"
1618                hayErrores=1
1619        fi
1620        popd
1621        # Compilar OpenGnsys Agent
1622        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Agent"
1623        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
1624        make && mv ogAdmAgent $INSTALL_TARGET/sbin
1625        if [ $? -ne 0 ]; then
1626                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Agent"
1627                hayErrores=1
1628        fi
1629        popd
1630        # Compilar OpenGnsys Client
1631        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Client"
1632        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
1633        make && mv ogAdmClient ../../../../client/shared/bin
1634        if [ $? -ne 0 ]; then
1635                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Client"
1636                hayErrores=1
1637        fi
1638        popd
1639
1640        return $hayErrores
1641}
1642
1643####################################################################
1644### Funciones de copia de la Interface de administración
1645####################################################################
1646
1647# Copiar carpeta de Interface
1648function copyInterfaceAdm ()
1649{
1650        local hayErrores=0
1651
1652        # Crear carpeta y copiar Interface
1653        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
1654        cp -ar $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client/interfaceAdm
1655        if [ $? -ne 0 ]; then
1656                echoAndLog "${FUNCNAME}(): error while copying Administration Interface Folder"
1657                hayErrores=1
1658        fi
1659
1660        return $hayErrores
1661}
1662
1663
1664####################################################################
1665### Funciones instalacion cliente opengnsys
1666####################################################################
1667
1668function copyClientFiles()
1669{
1670        local errstatus=0
1671
1672        echoAndLog "${FUNCNAME}(): Copying OpenGnsys Client files."
1673        cp -a $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
1674        if [ $? -ne 0 ]; then
1675                errorAndLog "${FUNCNAME}(): error while copying client estructure"
1676                errstatus=1
1677        fi
1678
1679        echoAndLog "${FUNCNAME}(): Copying OpenGnsys Cloning Engine files."
1680        mkdir -p $INSTALL_TARGET/client/lib/engine/bin
1681        cp -a $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
1682        if [ $? -ne 0 ]; then
1683                errorAndLog "${FUNCNAME}(): error while copying engine files"
1684                errstatus=1
1685        fi
1686
1687        if [ $errstatus -eq 0 ]; then
1688                echoAndLog "${FUNCNAME}(): client copy files success."
1689        else
1690                errorAndLog "${FUNCNAME}(): client copy files with errors"
1691        fi
1692
1693        return $errstatus
1694}
1695
1696
1697# Crear certificados para la firma de cargadores de arranque.
1698function createCerts ()
1699{
1700        local SSLCFGDIR=$INSTALL_TARGET/client/etc/ssl
1701        echoAndLog "${FUNCNAME}(): creating certificate files"
1702        mkdir -p $SSLCFGDIR/{certs,private}
1703        openssl req -new -x509 -newkey rsa:2048 -keyout $SSLCFGDIR/private/opengnsys.key -out $SSLCFGDIR/certs/opengnsys.crt -nodes -days 3650 -subj "/CN=OpenGnsys/"
1704        openssl x509 -in $SSLCFGDIR/certs/opengnsys.crt -out $SSLCFGDIR/certs/opengnsys.cer -outform DER
1705        echoAndLog "${FUNCNAME}(): certificate successfully created"
1706}
1707
1708
1709# Crear cliente OpenGnsys.
1710function clientCreate()
1711{
1712        if [ $# -ne 1 ]; then
1713                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1714                exit 1
1715        fi
1716
1717        local FILENAME="$1"
1718        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
1719
1720        # Descargar cliente, si es necesario.
1721        if [ -s $PROGRAMDIR/$FILENAME ]; then
1722                echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
1723                mv $PROGRAMDIR/$FILENAME $TARGETFILE
1724        else
1725                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
1726                oglivecli download $FILENAME
1727        fi
1728        if [ ! -s $TARGETFILE ]; then
1729                errorAndLog "${FUNCNAME}(): Error loading $FILENAME"
1730                return 1
1731        fi
1732
1733        # Montar imagen, copiar cliente ogclient y desmontar.
1734        echoAndLog "${FUNCNAME}(): Installing ogLive Client"
1735        echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | \
1736                        oglivecli install $FILENAME
1737
1738        echoAndLog "${FUNCNAME}(): Client generation success"
1739}
1740
1741
1742# Configuración básica de servicios de OpenGnsys
1743function openGnsysConfigure()
1744{
1745        local i=0
1746        local dev=""
1747        local CONSOLEURL
1748
1749        echoAndLog "${FUNCNAME}(): Copying init files."
1750        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
1751        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default /etc/default/opengnsys
1752        # Deshabilitar servicios de BitTorrent si no están instalados.
1753        if [ ! -e /usr/bin/bttrack ]; then
1754                sed -i 's/RUN_BTTRACKER="yes"/RUN_BTTRACKER="no"/; s/RUN_BTSEEDER="yes"/RUN_BTSEEDER="no"/' \
1755                        /etc/default/opengnsys
1756        fi
1757        echoAndLog "${FUNCNAME}(): Creating cron files."
1758        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
1759        echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
1760        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
1761        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/ogagentqueue.cron ] && $INSTALL_TARGET/bin/ogagentqueue.cron" > /etc/cron.d/ogagentqueue
1762
1763        echoAndLog "${FUNCNAME}(): Creating logrotate configuration files."
1764        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1765                $WORKDIR/opengnsys/server/etc/logrotate.tmpl > /etc/logrotate.d/opengnsysServer
1766
1767        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1768                $WORKDIR/opengnsys/repoman/etc/logrotate.tmpl > /etc/logrotate.d/opengnsysRepo
1769
1770        echoAndLog "${FUNCNAME}(): Creating OpenGnsys config files."
1771        for dev in ${DEVICE[*]}; do
1772                if [ -n "${SERVERIP[i]}" ]; then
1773                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1774                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1775                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1776                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1777                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer/ogAdmServer.cfg > $INSTALL_TARGET/etc/ogAdmServer-$dev.cfg
1778                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1779                                $WORKDIR/opengnsys/repoman/etc/ogAdmRepo.cfg.tmpl > $INSTALL_TARGET/etc/ogAdmRepo-$dev.cfg
1780                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1781                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1782                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1783                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1784                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent/ogAdmAgent.cfg > $INSTALL_TARGET/etc/ogAdmAgent-$dev.cfg
1785                        CONSOLEURL="https://${SERVERIP[i]}/opengnsys"
1786                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1787                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1788                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1789                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1790                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
1791                                $INSTALL_TARGET/www/controlacceso.php > $INSTALL_TARGET/www/controlacceso-$dev.php
1792                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1793                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
1794                                $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient/ogAdmClient.cfg > $INSTALL_TARGET/client/etc/ogAdmClient-$dev.cfg
1795                        if [ "$dev" == "$DEFAULTDEV" ]; then
1796                                OPENGNSYS_CONSOLEURL="$CONSOLEURL"
1797                        fi
1798                fi
1799                let i++
1800        done
1801        ln -f $INSTALL_TARGET/etc/ogAdmServer-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmServer.cfg
1802        ln -f $INSTALL_TARGET/etc/ogAdmRepo-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmRepo.cfg
1803        ln -f $INSTALL_TARGET/etc/ogAdmAgent-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmAgent.cfg
1804        ln -f $INSTALL_TARGET/client/etc/ogAdmClient-$DEFAULTDEV.cfg $INSTALL_TARGET/client/etc/ogAdmClient.cfg
1805        ln -f $INSTALL_TARGET/www/controlacceso-$DEFAULTDEV.php $INSTALL_TARGET/www/controlacceso.php
1806
1807        # Configuración del motor de clonación.
1808        # - Zona horaria del servidor.
1809        TZ=$(timedatectl status|awk -F"[:()]" '/Time.*zone/ {print $2}')
1810        cat << EOT >> $INSTALL_TARGET/client/etc/engine.cfg
1811# OpenGnsys Server timezone.
1812TZ="${TZ// /}"
1813EOT
1814
1815        # Revisar permisos generales.
1816        if [ -x $INSTALL_TARGET/bin/checkperms ]; then
1817                echoAndLog "${FUNCNAME}(): Checking permissions."
1818                OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENT_USER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" checkperms
1819        fi
1820
1821        # Evitar inicio de duplicado en Ubuntu 14.04 (Upstart y SysV Init).
1822        if [ -f /etc/init/${MYSQLSERV}.conf -a -n "$(which initctl 2>/dev/null)" ]; then
1823                service=$MYSQLSERV
1824                $DISABLESERVICE
1825        fi
1826
1827        # Actualizar tokens de autenticación e iniciar los servicios.
1828        service="opengnsys"
1829        $ENABLESERVICE
1830        if [ -x $INSTALL_TARGET/bin/settoken ]; then
1831                echoAndLog "${FUNCNAME}(): Setting authentication tokens and starting OpenGnsys services."
1832                $INSTALL_TARGET/bin/settoken "$OPENGNSYS_DB_USER"
1833                $INSTALL_TARGET/bin/settoken -f
1834        else
1835                echoAndLog "${FUNCNAME}(): Starting OpenGnsys services."
1836                $STARTSERVICE
1837        fi
1838}
1839
1840
1841#####################################################################
1842#######  Función de resumen informativo de la instalación
1843#####################################################################
1844
1845function installationSummary()
1846{
1847        local VERSIONFILE REVISION
1848
1849        # Crear fichero de versión y revisión, si no existe.
1850        VERSIONFILE="$INSTALL_TARGET/doc/VERSION.json"
1851        [ -f $VERSIONFILE ] || echo '{ "project": "OpenGnsys" }' >$VERSIONFILE
1852        # Incluir datos de revisión, si se está instalando desde el repositorio
1853        # de código o si no está incluida en el fichero de versión.
1854        if [ $REMOTE -eq 1 ] || [ -z "$(jq -r '.release' $VERSIONFILE)" ]; then
1855                # Revisión: rAñoMesDía.Gitcommit (8 caracteres de fecha y 7 primeros de commit).
1856                RELEASE=$(curl -s "$API_URL/branches/$BRANCH" | jq -r '"r" + (.commit.commit.committer.date | split("-") | join("")[:8]) + "." + (.commit.sha[:7])' 2>/dev/null)
1857                # Obtener revisión para etiqueta de versión en vez de rama de código.
1858                [ -z "$RELEASE" ] && RELEASE=$(curl -s $(curl -s "$API_URL/tags" | jq -r ".[] | select(.name==\"$BRANCH\").commit.url" 2>/dev/null) | jq -r '"r" + (.commit.committer.date | split("-") | join("")[:8]) + "." + .sha[:7]' 2>/dev/null)
1859                jq ".release=\"$RELEASE\"" $VERSIONFILE | sponge $VERSIONFILE
1860        fi
1861        VERSION="$(jq -r '[.project, .version, .codename, .release] | join(" ")' $VERSIONFILE 2>/dev/null)"
1862
1863        # Mostrar información.
1864        echo
1865        echoAndLog "OpenGnsys Installation Summary"
1866        echo       "=============================="
1867        echoAndLog "Project version:                  $VERSION"
1868        echoAndLog "Installation directory:           $INSTALL_TARGET"
1869        echoAndLog "Installation log file:            $LOG_FILE"
1870        echoAndLog "Repository directory:             $INSTALL_TARGET/images"
1871        echoAndLog "DHCP configuration directory:     $DHCPCFGDIR"
1872        echoAndLog "TFTP configuration directory:     $TFTPCFGDIR"
1873        echoAndLog "Installed ogLive client:          $(oglivecli list | awk '{print $2}')"
1874        echoAndLog "Samba configuration directory:    $SAMBACFGDIR"
1875        echoAndLog "Web Console URL:                  $OPENGNSYS_CONSOLEURL"
1876        echoAndLog "Web Console access data:          entered by the user"
1877        if grep -q "^RUN_BTTRACK.*no" /etc/default/opengnsys; then
1878                echoAndLog "BitTorrent service is disabled."
1879        fi
1880        echo
1881        echoAndLog "Post-Installation Instructions:"
1882        echo       "==============================="
1883        echoAndLog "You can improve server security by configuring firewall and SELinux,"
1884        echoAndLog "   running \"$INSTALL_TARGET/lib/security-config\" script as root."
1885        echoAndLog "It's strongly recommended to synchronize this server with an NTP server."
1886        echoAndLog "Review or edit all configuration files."
1887        echoAndLog "Insert DHCP configuration data and restart service."
1888        echoAndLog "Optional: If you want to use BURG as boot manager, run"
1889        echoAndLog "   \"curl $DOWNLOADURL/burg.tgz -o $INSTALL_TARGET/client/lib/burg.tgz\" as root."
1890        echoAndLog "Optional: Log-in as Web Console admin user."
1891        echoAndLog " - Review default Organization data and assign access to users."
1892        echoAndLog "Log-in as Web Console organization user."
1893        echoAndLog " - Insert OpenGnsys data (labs, computers, menus, etc)."
1894echo
1895}
1896
1897
1898
1899#####################################################################
1900####### Proceso de instalación de OpenGnsys
1901#####################################################################
1902
1903# Sólo ejecutable por usuario root
1904if [ "$(whoami)" != 'root' ]; then
1905        echo "ERROR: this program must run under root privileges!!"
1906        exit 1
1907fi
1908
1909globalSetup $MY_BRANCH
1910# Comprobar instalación previa.
1911if cat $INSTALL_TARGET/doc/VERSION.* &>/dev/null; then
1912        echo "ERROR: OpenGnsys is already installed. Run \"$INSTALL_TARGET/lib/opengnsys_update.sh\" as root to update."
1913        exit 2
1914fi
1915
1916echoAndLog "OpenGnsys installation begins at $(date)"
1917# Introducir datos de configuración y establecer variables globales.
1918userData
1919
1920mkdir -p $WORKDIR
1921pushd $WORKDIR
1922
1923# Detectar datos iniciales de auto-configuración del instalador.
1924autoConfigure
1925
1926# Detectar parámetros de red y comprobar si hay conexión.
1927getNetworkSettings
1928if [ $? -ne 0 ]; then
1929        errorAndLog "Error reading default network settings."
1930        exit 1
1931fi
1932checkNetworkConnection
1933if [ $? -ne 0 ]; then
1934        errorAndLog "Error connecting to server. Causes:"
1935        errorAndLog " - Network is unreachable, review devices parameters."
1936        errorAndLog " - You are inside a private network, configure the proxy service."
1937        errorAndLog " - Server is temporally down, try agian later."
1938        exit 1
1939fi
1940
1941# Detener servicios de OpenGnsys, si están activos previamente.
1942[ -f /etc/init.d/opengnsys ] && /etc/init.d/opengnsys stop
1943
1944# Actualizar repositorios
1945updatePackageList
1946
1947# Instalación de dependencias (paquetes de sistema operativo).
1948declare -a notinstalled
1949checkDependencies DEPENDENCIES notinstalled
1950if [ $? -ne 0 ]; then
1951        installDependencies notinstalled
1952        if [ $? -ne 0 ]; then
1953                echoAndLog "Error while installing some dependeces, please verify your server installation before continue"
1954                exit 1
1955        fi
1956fi
1957if [ -n "$INSTALLEXTRADEPS" ]; then
1958        echoAndLog "Installing extra dependencies"
1959        for (( i=0; i<${#INSTALLEXTRADEPS[*]}; i++ )); do
1960                eval ${INSTALLEXTRADEPS[i]}
1961        done
1962fi
1963
1964# Detectar datos de auto-configuración después de instalar paquetes.
1965autoConfigurePost
1966
1967# Arbol de directorios de OpenGnsys.
1968createDirs ${INSTALL_TARGET}
1969if [ $? -ne 0 ]; then
1970        errorAndLog "Error while creating directory paths!"
1971        exit 1
1972fi
1973
1974# Si es necesario, descarga el repositorio de código en directorio temporal
1975if [ $REMOTE -eq 1 ]; then
1976        downloadCode $GIT_REPO
1977        if [ $? -ne 0 ]; then
1978                errorAndLog "Error while getting code from the repository"
1979                exit 1
1980        fi
1981else
1982        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
1983fi
1984
1985# TLS
1986gatherCertsInfo
1987if [ $? -ne 0 ]; then
1988        errorAndLog 'Not all required certificates have been provided, or privkey or DNS issues'
1989        exit 1
1990fi
1991[ $TLS_DATA_CA_EXPIRY ] && genAllCerts                  ## el usuario no nos ha dado sus certificados: generamos unos
1992installAllCerts
1993[ $TLS_DATA_CA_EXPIRY ] && makeCommonNamesResolvable    ## el usuario no nos ha dado sus certificados: configuramos resolución de nombres en /etc/hosts
1994configureStunnel
1995if [ $? -ne 0 ]; then
1996        errorAndLog 'Error while setting stunnel up'
1997        exit 1
1998fi
1999
2000# Compilar código fuente de los servicios de OpenGnsys.
2001servicesCompilation
2002if [ $? -ne 0 ]; then
2003        errorAndLog "Error while compiling OpenGnsys services"
2004        exit 1
2005fi
2006
2007# Copiar carpeta Interface entre administración y motor de clonación.
2008copyInterfaceAdm
2009if [ $? -ne 0 ]; then
2010        errorAndLog "Error while copying Administration Interface"
2011        exit 1
2012fi
2013
2014# Configuración de TFTP.
2015tftpConfigure
2016
2017# Configuración de Samba.
2018smbConfigure
2019if [ $? -ne 0 ]; then
2020        errorAndLog "Error while configuring Samba server!"
2021        exit 1
2022fi
2023
2024# Configuración de Rsync.
2025rsyncConfigure
2026
2027# Configuración ejemplo DHCP.
2028dhcpConfigure
2029if [ $? -ne 0 ]; then
2030        errorAndLog "Error while copying your dhcp server files!"
2031        exit 1
2032fi
2033
2034# Copiar ficheros de servicios OpenGnsys Server.
2035copyServerFiles ${INSTALL_TARGET}
2036if [ $? -ne 0 ]; then
2037        errorAndLog "Error while copying the server files!"
2038        exit 1
2039fi
2040INSTVERSION=$(jq -r '.version' $INSTALL_TARGET/doc/VERSION.json)
2041
2042# Instalar base de datos de OpenGnsys Admin.
2043isInArray notinstalled "mysql-server" || isInArray notinstalled "mariadb-server"
2044if [ $? -eq 0 ]; then
2045        # Enable database manager (MySQL, if missing, MariaDB).
2046        service=$MYSQLSERV
2047        $ENABLESERVICE
2048        if [ $? != 0 ]; then
2049                service=$MARIADBSERV
2050                $ENABLESERVICE
2051        fi
2052        # Start database manager.
2053        $STARTSERVICE
2054        # Asignar clave del usuario "root".
2055        mysqlSetRootPassword "${MYSQL_ROOT_PASSWORD}"
2056else
2057        # Si ya está instalado el gestor de bases de datos, obtener clave de "root".
2058        mysqlGetRootPassword
2059fi
2060
2061# Copy MySQL configuration template
2062cp $WORKDIR/opengnsys/server/etc/mysqld-og.cnf $MYSQLCFGDIR 2>/dev/null
2063# Restart database manager.
2064$STARTSERVICE
2065
2066mysqlTestConnection "${MYSQL_ROOT_PASSWORD}"
2067if [ $? -ne 0 ]; then
2068        errorAndLog "Error while connection to mysql"
2069        exit 1
2070fi
2071mysqlDbExists ${OPENGNSYS_DATABASE}
2072if [ $? -ne 0 ]; then
2073        echoAndLog "Creating Web Console database"
2074        mysqlCreateDb ${OPENGNSYS_DATABASE}
2075        if [ $? -ne 0 ]; then
2076                errorAndLog "Error while creating Web Console database"
2077                exit 1
2078        fi
2079else
2080        echoAndLog "Web Console database exists, ommiting creation"
2081fi
2082
2083mysqlCheckUserExists ${OPENGNSYS_DB_USER}
2084if [ $? -ne 0 ]; then
2085        echoAndLog "Creating user in database"
2086        mysqlCreateAdminUserToDb ${OPENGNSYS_DATABASE} ${OPENGNSYS_DB_USER} "${OPENGNSYS_DB_PASSWD}"
2087        if [ $? -ne 0 ]; then
2088                errorAndLog "Error while creating database user"
2089                exit 1
2090        fi
2091
2092fi
2093
2094mysqlCheckDbIsEmpty ${OPENGNSYS_DATABASE}
2095if [ $? -eq 0 ]; then
2096        echoAndLog "Creating tables..."
2097        if [ -f $WORKDIR/$OPENGNSYS_DB_CREATION_FILE ]; then
2098                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_CREATION_FILE
2099        else
2100                errorAndLog "Unable to locate $WORKDIR/$OPENGNSYS_DB_CREATION_FILE!!"
2101                exit 1
2102        fi
2103else
2104        # Si existe fichero ogBDAdmin-VersLocal-VersRepo.sql; aplicar cambios.
2105        REPOVERSION=$(jq -r '.version' $WORKDIR/opengnsys/doc/VERSION.json)
2106        OPENGNSYS_DB_UPDATE_FILE="opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
2107        if [ -f $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE ]; then
2108                echoAndLog "Updating tables from version $INSTVERSION to $REPOVERSION"
2109                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE
2110        else
2111                echoAndLog "Database unchanged."
2112        fi
2113fi
2114# Eliminar fichero temporal con credenciales de acceso a MySQL.
2115rm -f $TMPMYCNF
2116
2117# Copiando páqinas web.
2118installWebFiles
2119# Configurar variables de PHP
2120configurePHPvars $TLS_DATA_OGADMSRV_CN $TLS_DATA_OGADMSRV_LISTEN_PORT
2121# Descargar/descomprimir archivos descargables.
2122installDownloadableFiles
2123# Generar páqinas web de documentación de la API
2124makeDoxygenFiles
2125
2126# Creando configuración de Apache.
2127installWebConsoleApacheConf $INSTALL_TARGET $APACHECFGDIR
2128if [ $? -ne 0 ]; then
2129        errorAndLog "Error configuring Apache for OpenGnsys Admin"
2130        exit 1
2131fi
2132
2133popd
2134
2135# Crear la estructura de los accesos al servidor desde el cliente (shared)
2136copyClientFiles
2137if [ $? -ne 0 ]; then
2138        errorAndLog "Error creating client structure"
2139fi
2140
2141# Crear certificado para firmar cargadores
2142createCerts
2143
2144# Crear la estructura del cliente de OpenGnsys.
2145for i in $OGLIVE; do
2146        if ! clientCreate "$i"; then
2147                errorAndLog "Error creating client $i"
2148                exit 1
2149        fi
2150done
2151
2152# Configuración de servicios de OpenGnsys
2153openGnsysConfigure
2154
2155# Mostrar sumario de la instalación e instrucciones de post-instalación.
2156installationSummary
2157
2158rm -rf $WORKDIR
2159echoAndLog "OpenGnsys installation finished at $(date)"
2160exit 0
2161
Note: See TracBrowser for help on using the repository browser.