source: installer/opengnsys_installer_devel_esxi.sh @ 4b0defb

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 4b0defb was eda2f74, checked in by Natalia Serrano <natalia.serrano@…>, 17 months ago

Remove "set -x"

  • 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        echoAndLog "${FUNCNAME}(): Checking OpenGnsys server connectivity."
858        OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"opengnsys.es"}
859        if which curl &>/dev/null; then
860                curl --connect-timeout 10 --retry 5 --retry-delay 5 --max-time 30 "https://$OPENGNSYS_SERVER/" -o /dev/null && \
861                        curl --connect-timeout 10 --retry 5 --retry-delay 5 --max-time 30 "http://$OPENGNSYS_SERVER/" -o /dev/null
862        elif which wget &>/dev/null; then
863                wget --spider -q "https://$OPENGNSYS_SERVER/" && \
864                        wget --spider -q "http://$OPENGNSYS_SERVER/"
865        else
866                echoAndLog "${FUNCNAME}(): Cannot execute \"wget\" nor \"curl\"."
867                return 1
868        fi
869}
870
871# Convierte nº de bits (notación CIDR) en máscara de red (gracias a FriedZombie en openwrt.org).
872cidr2mask ()
873{
874        # Number of args to shift, 255..255, first non-255 byte, zeroes
875        set -- $[ 5 - ($1 / 8) ] 255 255 255 255 $[ (255 << (8 - ($1 % 8))) & 255 ] 0 0 0
876        [ $1 -gt 1 ] && shift $1 || shift
877        echo ${1-0}.${2-0}.${3-0}.${4-0}
878}
879
880# Obtener los parámetros de red de la interfaz por defecto.
881function getNetworkSettings()
882{
883        # Arrays globales definidas:
884        # - DEVICE:     nombres de dispositivos de red activos.
885        # - SERVERIP:   IPs locales del servidor.
886        # - NETIP:      IPs de redes.
887        # - NETMASK:    máscaras de red.
888        # - NETBROAD:   IPs de difusión de redes.
889        # - ROUTERIP:   IPs de routers.
890        # Otras variables globales:
891        # - DEFAULTDEV: dispositivo de red por defecto.
892        # - DNSIP:      IP del servidor DNS principal.
893
894        local i=0
895        local dev=""
896
897        echoAndLog "${FUNCNAME}(): Detecting network parameters."
898        DEVICE=( $(ip -o link show up | awk '!/loopback/ {sub(/[:@].*/,"",$2); print $2}') )
899        if [ -z "$DEVICE" ]; then
900                errorAndLog "${FUNCNAME}(): Network devices not detected."
901                exit 1
902        fi
903        for dev in ${DEVICE[*]}; do
904                SERVERIP[i]=$(ip -o addr show dev "$dev" | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4); exit;}')
905                if [ -n "${SERVERIP[i]}" ]; then
906                        NETMASK[i]=$( cidr2mask $(ip -o addr show dev "$dev" | awk '$3~/inet$/ {sub (/.*\//, "", $4); print ($4); exit;}') )
907                        NETBROAD[i]=$(ip -o addr show dev "$dev" | awk '$3~/inet$/ {print ($6); exit;}')
908                        NETIP[i]=$(ip route list proto kernel | awk -v d="$dev" '$3==d && /src/ {sub (/\/.*/,""); print $1; exit;}')
909                        ROUTERIP[i]=$(ip route list default | awk -v d="$dev" '$5==d {print $3; exit;}')
910                        if [ $DHCPNET == ${NETIP[i]} ]; then
911                                DEFAULTDEV="$dev"
912                        else
913                                DEFAULTDEV=${DEFAULTDEV:-"$dev"}
914                        fi
915                fi
916                let i++
917        done
918        DNSIP=$(systemd-resolve --status 2>/dev/null | awk '/DNS Servers:/ {print $3; exit;}')
919        [ -z "$DNSIP" ] && DNSIP=$(awk '/nameserver/ {print $2; exit;}' /etc/resolv.conf)
920        if [ -z "${NETIP[*]}" -o -z "${NETMASK[*]}" ]; then
921                errorAndLog "${FUNCNAME}(): Network not detected."
922                exit 1
923        fi
924
925        # Variables de ejecución de Apache
926        # - APACHE_RUN_USER
927        # - APACHE_RUN_GROUP
928        if [ -f $APACHECFGDIR/envvars ]; then
929                source $APACHECFGDIR/envvars
930        fi
931        APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
932        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
933
934        echoAndLog "${FUNCNAME}(): Default network device: $DEFAULTDEV."
935}
936
937
938############################################################
939### Esqueleto para el Servicio pxe y contenedor tftpboot ###
940############################################################
941
942function tftpConfigure()
943{
944        echoAndLog "${FUNCNAME}(): Configuring TFTP service."
945        # Habilitar TFTP y reiniciar Inetd.
946        if [ -n "$TFTPSERV" ]; then
947                if [ -f $INETDCFGDIR/$TFTPSERV ]; then
948                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/$TFTPSERV
949                else
950                        service=$TFTPSERV
951                        $ENABLESERVICE; $STARTSERVICE
952                fi
953        fi
954        service=$INETDSERV
955        $ENABLESERVICE; $STARTSERVICE
956
957        # comprobamos el servicio tftp
958        sleep 1
959        testPxe
960}
961
962# Comprueba que haya conexión al servicio TFTP/PXE.
963function testPxe ()
964{
965        echoAndLog "${FUNCNAME}(): Checking TFTP service... please wait."
966        echo "test" >$TFTPCFGDIR/testpxe
967        tftp -v 127.0.0.1 -c get testpxe /tmp/testpxe && echoAndLog "TFTP service is OK." || errorAndLog "TFTP service is down."
968        rm -f $TFTPCFGDIR/testpxe /tmp/testpxe
969}
970
971
972########################################################################
973## Configuración servicio Samba
974########################################################################
975
976# Configurar servicios Samba.
977function smbConfigure()
978{
979        echoAndLog "${FUNCNAME}(): Configuring Samba service."
980
981        backupFile $SAMBACFGDIR/smb.conf
982
983        # Copiar plantailla de recursos para OpenGnsys
984        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
985                $WORKDIR/opengnsys/server/etc/smb-og.conf.tmpl > $SAMBACFGDIR/smb-og.conf
986        # Configurar y recargar Samba"
987        perl -pi -e "s/WORKGROUP/OPENGNSYS/; s/server string \=.*/server string \= OpenGnsys Samba Server/" $SAMBACFGDIR/smb.conf
988        if ! grep -q "smb-og" $SAMBACFGDIR/smb.conf; then
989                echo "include = $SAMBACFGDIR/smb-og.conf" >> $SAMBACFGDIR/smb.conf
990        fi
991        service=$SAMBASERV
992        $ENABLESERVICE; $STARTSERVICE
993        if [ $? -ne 0 ]; then
994                errorAndLog "${FUNCNAME}(): error while configure Samba"
995                return 1
996        fi
997        # Crear clave para usuario de acceso a los recursos.
998        echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | smbpasswd -a -s $OPENGNSYS_CLIENT_USER
999
1000        echoAndLog "${FUNCNAME}(): Added Samba configuration."
1001        return 0
1002}
1003
1004
1005########################################################################
1006## Configuración servicio Rsync
1007########################################################################
1008
1009# Configurar servicio Rsync.
1010function rsyncConfigure()
1011{
1012        echoAndLog "${FUNCNAME}(): Configuring Rsync service."
1013
1014        backupFile $RSYNCCFGDIR/rsyncd.conf
1015
1016        # Configurar acceso a Rsync.
1017        sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENT_USER/g" \
1018                $WORKDIR/opengnsys/repoman/etc/rsyncd.conf.tmpl > $RSYNCCFGDIR/rsyncd.conf
1019        # Habilitar Rsync y reiniciar Inetd.
1020        if [ -n "$RSYNCSERV" ]; then
1021                if [ -f /etc/default/rsync ]; then
1022                        perl -pi -e 's/RSYNC_ENABLE=.*/RSYNC_ENABLE=inetd/' /etc/default/rsync
1023                fi
1024                if [ -f $INETDCFGDIR/rsync ]; then
1025                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/rsync
1026                else
1027                        cat << EOT > $INETDCFGDIR/rsync
1028service rsync
1029{
1030        disable = no
1031        socket_type = stream
1032        wait = no
1033        user = root
1034        server = $(which rsync)
1035        server_args = --daemon
1036        log_on_failure += USERID
1037        flags = IPv6
1038}
1039EOT
1040                fi
1041                service=$RSYNCSERV $ENABLESERVICE
1042                service=$INETDSERV $STARTSERVICE
1043        fi
1044
1045        echoAndLog "${FUNCNAME}(): Added Rsync configuration."
1046        return 0
1047}
1048
1049
1050########################################################################
1051## Configuración servicio DHCP
1052########################################################################
1053
1054# Configurar servicios DHCP.
1055function dhcpConfigure()
1056{
1057        echoAndLog "${FUNCNAME}(): Sample DHCP configuration."
1058
1059        local errcode=0
1060        local i=0
1061        local dev=""
1062
1063        backupFile $DHCPCFGDIR/dhcpd.conf
1064        for dev in ${DEVICE[*]}; do
1065                if [ -n "${SERVERIP[i]}" ]; then
1066                        backupFile $DHCPCFGDIR/dhcpd-$dev.conf
1067                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1068                            -e "s/NETIP/${NETIP[i]}/g" \
1069                            -e "s/NETMASK/${NETMASK[i]}/g" \
1070                            -e "s/NETBROAD/${NETBROAD[i]}/g" \
1071                            -e "s/ROUTERIP/${ROUTERIP[i]}/g" \
1072                            -e "s/DNSIP/$DNSIP/g" \
1073                            $WORKDIR/opengnsys/server/etc/dhcpd.conf.tmpl > $DHCPCFGDIR/dhcpd-$dev.conf || errcode=1
1074                fi
1075                let i++
1076        done
1077        if [ $errcode -ne 0 ]; then
1078                errorAndLog "${FUNCNAME}(): error while configuring DHCP server"
1079                return 1
1080        fi
1081        ln -f $DHCPCFGDIR/dhcpd-$DEFAULTDEV.conf $DHCPCFGDIR/dhcpd.conf
1082        service=$DHCPSERV
1083        $ENABLESERVICE; $STARTSERVICE
1084        echoAndLog "${FUNCNAME}(): Sample DHCP configured in \"$DHCPCFGDIR\"."
1085        return 0
1086}
1087
1088
1089#####################################################################
1090####### Funciones específicas de la instalación de Opengnsys
1091#####################################################################
1092
1093# Copiar ficheros del OpenGnsys Web Console.
1094function installWebFiles()
1095{
1096        local COMPATDIR f
1097        local SLIMFILE="slim-2.6.1.zip"
1098        local SWAGGERFILE="swagger-ui-2.2.5.zip"
1099
1100        echoAndLog "${FUNCNAME}(): Installing web files..."
1101        # Copiar ficheros.
1102        cp -a $WORKDIR/opengnsys/admin/WebConsole/* $INSTALL_TARGET/www   #*/ comentario para Doxygen.
1103        if [ $? != 0 ]; then
1104                errorAndLog "${FUNCNAME}(): Error copying web files."
1105                exit 1
1106        fi
1107
1108        # Descomprimir librerías: Slim y Swagger-UI.
1109        unzip -o $WORKDIR/opengnsys/admin/$SLIMFILE -d $INSTALL_TARGET/www/rest
1110        unzip -o $WORKDIR/opengnsys/admin/$SWAGGERFILE -d $INSTALL_TARGET/www/rest
1111
1112        # Compatibilidad con dispositivos móviles.
1113        COMPATDIR="$INSTALL_TARGET/www/principal"
1114        for f in acciones administracion aula aulas hardwares imagenes menus repositorios softwares; do
1115                sed 's/clickcontextualnodo/clicksupnodo/g' $COMPATDIR/$f.php > $COMPATDIR/$f.device.php
1116        done
1117        cp -a $COMPATDIR/imagenes.device.php $COMPATDIR/imagenes.device4.php
1118        # Acceso al manual de usuario
1119        ln -fs ../doc/userManual $INSTALL_TARGET/www/userManual
1120        # Ficheros de log de la API REST.
1121        touch $INSTALL_TARGET/log/{ogagent,remotepc,rest}.log
1122
1123        echoAndLog "${FUNCNAME}(): Web files installed successfully."
1124}
1125
1126function configurePHPvars()
1127{
1128    OGADMSRV_HOSTNAME=$1
1129    OGADMSRV_PORT=$2
1130    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
1131}
1132
1133# Copiar ficheros en la zona de descargas de OpenGnsys Web Console.
1134function installDownloadableFiles()
1135{
1136        local VERSIONFILE OGVERSION FILENAME TARGETFILE
1137
1138        # Obtener versión a descargar.
1139        VERSIONFILE="$INSTALL_TARGET/doc/VERSION.json"
1140        OGVERSION="$(jq -r ".ogagent // \"$INSTVERSION\"" $VERSIONFILE 2>/dev/null || echo "$INSTVERSION")"
1141        FILENAME="ogagentpkgs-$OGVERSION.tar.gz"
1142        TARGETFILE=$WORKDIR/$FILENAME
1143
1144        # Descargar archivo comprimido, si es necesario.
1145        if [ -s $PROGRAMDIR/$FILENAME ]; then
1146                echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
1147                mv $PROGRAMDIR/$FILENAME $TARGETFILE
1148        else
1149                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
1150                curl --retry 5 --retry-delay 5 --max-time 30 $DOWNLOADURL/$FILENAME -o $TARGETFILE
1151        fi
1152        if [ ! -s $TARGETFILE ]; then
1153                errorAndLog "${FUNCNAME}(): Cannot download $FILENAME"
1154                return 1
1155        fi
1156
1157        # Descomprimir fichero en zona de descargas.
1158        tar xvzf $TARGETFILE -C $INSTALL_TARGET/www/descargas
1159        if [ $? != 0 ]; then
1160                errorAndLog "${FUNCNAME}(): Error uncompressing archive."
1161                exit 1
1162        fi
1163}
1164
1165# Configuración específica de Apache.
1166function installWebConsoleApacheConf()
1167{
1168        if [ $# -ne 2 ]; then
1169                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1170                exit 1
1171        fi
1172
1173        local path_opengnsys_base="$1"
1174        local path_apache2_confd="$2"
1175        local CONSOLEDIR=${path_opengnsys_base}/www
1176        local sockfile
1177
1178        if [ ! -d $path_apache2_confd ]; then
1179                errorAndLog "${FUNCNAME}(): path to apache2 conf.d can not found, verify your server installation"
1180                return 1
1181        fi
1182
1183        mkdir -p $path_apache2_confd/{sites-available,sites-enabled}
1184
1185        echoAndLog "${FUNCNAME}(): creating apache2 config file.."
1186
1187        # Avtivar PHP-FPM.
1188        echoAndLog "${FUNCNAME}(): configuring PHP-FPM"
1189        service=$PHPFPMSERV
1190        $ENABLESERVICE; $STARTSERVICE
1191        sockfile=$(find /run/php -name "php*.sock" -type s -print 2>/dev/null | tail -1)
1192
1193        # Activar módulos de Apache.
1194        $APACHEENABLEMODS
1195        # Activar HTTPS.
1196        $APACHEENABLESSL
1197        $APACHEMAKECERT
1198        # Genera configuración de consola web a partir del fichero plantilla.
1199        if [ -n "$(apachectl -v | grep "2\.[0-2]")" ]; then
1200                # Configuración para versiones anteriores de Apache.
1201                sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
1202                        $WORKDIR/opengnsys/server/etc/apache-prev2.4.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}
1203        else
1204                # Configuración específica a partir de Apache 2.4
1205                if [ -n "$sockfile" ]; then
1206                        sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
1207                            -e "s,proxy:fcgi:.*,proxy:unix:${sockfile%% *}|fcgi://localhost\",g" \
1208                                $WORKDIR/opengnsys/server/etc/apache.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf
1209                else
1210                        sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
1211                                $WORKDIR/opengnsys/server/etc/apache.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf
1212                fi
1213        fi
1214        $APACHEENABLEOG
1215        if [ $? -ne 0 ]; then
1216                errorAndLog "${FUNCNAME}(): config file can't be linked to apache conf, verify your server installation"
1217                return 1
1218        fi
1219        echoAndLog "${FUNCNAME}(): config file created and linked, restarting apache daemon"
1220        service=$APACHESERV
1221        $ENABLESERVICE; $STARTSERVICE
1222        return 0
1223}
1224
1225
1226# Crear documentación Doxygen para la consola web.
1227function makeDoxygenFiles()
1228{
1229        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
1230        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
1231                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
1232        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
1233                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
1234                return 1
1235        fi
1236        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
1237        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
1238}
1239
1240
1241# Crea la estructura base de la instalación de opengnsys
1242function createDirs()
1243{
1244        if [ $# -ne 1 ]; then
1245                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1246                exit 1
1247        fi
1248
1249        local path_opengnsys_base="$1"
1250
1251        # Crear estructura de directorios.
1252        echoAndLog "${FUNCNAME}(): creating directory paths in $path_opengnsys_base"
1253        mkdir -p $path_opengnsys_base
1254        mkdir -p $path_opengnsys_base/bin
1255        mkdir -p $path_opengnsys_base/client/{cache,images,log}
1256        mkdir -p $path_opengnsys_base/doc
1257        mkdir -p $path_opengnsys_base/etc
1258        mkdir -p $path_opengnsys_base/lib
1259        mkdir -p $path_opengnsys_base/log/clients
1260        ln -fs $path_opengnsys_base/log /var/log/opengnsys
1261        mkdir -p $path_opengnsys_base/sbin
1262        mkdir -p $path_opengnsys_base/www
1263        mkdir -p $path_opengnsys_base/images/groups
1264        mkdir -p $TFTPCFGDIR
1265        ln -fs $TFTPCFGDIR $path_opengnsys_base/tftpboot
1266        mkdir -p $path_opengnsys_base/tftpboot/{menu.lst,grub}
1267        if [ $? -ne 0 ]; then
1268                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
1269                return 1
1270        fi
1271
1272        # Crear usuario ficticio.
1273        if id -u $OPENGNSYS_CLIENT_USER &>/dev/null; then
1274                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENT_USER\" is already created"
1275        else
1276                echoAndLog "${FUNCNAME}(): creating OpenGnsys user"
1277                useradd $OPENGNSYS_CLIENT_USER 2>/dev/null
1278                if [ $? -ne 0 ]; then
1279                        errorAndLog "${FUNCNAME}(): error creating OpenGnsys user"
1280                        return 1
1281                fi
1282        fi
1283
1284        # Mover el fichero de registro de instalación al directorio de logs.
1285        echoAndLog "${FUNCNAME}(): moving installation log file"
1286        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
1287        chmod 600 $LOG_FILE
1288
1289        echoAndLog "${FUNCNAME}(): directory paths created"
1290        return 0
1291}
1292
1293# Copia ficheros de configuración y ejecutables genéricos del servidor.
1294function copyServerFiles ()
1295{
1296        if [ $# -ne 1 ]; then
1297                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1298                exit 1
1299        fi
1300
1301        local path_opengnsys_base="$1"
1302
1303        # Lista de ficheros y directorios origen y de directorios destino.
1304        local SOURCES=( server/tftpboot \
1305                        /usr/lib/shim/shimx64.efi.signed \
1306                        /usr/lib/grub/x86_64-efi-signed/grubnetx64.efi.signed \
1307                        server/bin \
1308                        repoman/bin \
1309                        server/lib \
1310                        admin/Sources/Services/ogAdmServerAux
1311                        admin/Sources/Services/ogAdmRepoAux
1312                        installer/opengnsys_uninstall.sh \
1313                        installer/opengnsys_update.sh \
1314                        installer/opengnsys_export.sh \
1315                        installer/opengnsys_import.sh \
1316                        doc )
1317        local TARGETS=( tftpboot \
1318                        tftpboot \
1319                        tftpboot/grubx64.efi \
1320                        bin \
1321                        bin \
1322                        lib \
1323                        sbin \
1324                        sbin \
1325                        lib \
1326                        lib \
1327                        lib \
1328                        lib \
1329                        doc )
1330
1331        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
1332                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
1333                exit 1
1334        fi
1335
1336        # Copiar ficheros.
1337        echoAndLog "${FUNCNAME}(): copying files to server directories"
1338
1339        pushd $WORKDIR/opengnsys
1340        local i
1341        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
1342                if [ -f "${SOURCES[$i]}" ]; then
1343                        echoAndLog "Copying ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1344                        cp -a "${SOURCES[$i]}" "${path_opengnsys_base}/${TARGETS[$i]}"
1345                elif [ -d "${SOURCES[$i]}" ]; then
1346                        echoAndLog "Copying content of ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1347                        cp -a "${SOURCES[$i]}"/* "${path_opengnsys_base}/${TARGETS[$i]}"
1348                else
1349                        warningAndLog "Unable to copy ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1350                fi
1351        done
1352
1353        popd
1354}
1355
1356####################################################################
1357### Funciones de TLS
1358####################################################################
1359
1360CA_DIR=/root/CA
1361OG_BASEDIR=/opt/opengnsys
1362
1363function gatherCertsInfo()
1364{
1365    ERRORS=0
1366    ## BUG cuando REMOTE=1, $WORKDIR/opengnsys es el contenido del zip (producido al vuelo con 'git archive'), y naturalmente no contiene ./user-certs
1367    ##     este código debe buscar los certificados en otro sitio adicional
1368    if [ -f $WORKDIR/opengnsys/user-certs/ca.crt.pem ]; then
1369        echoAndLog "CA provided by the user, checking presence of all certificates"
1370
1371        TLS_DATA_CA_CERTFILE=$WORKDIR/opengnsys/user-certs/ca.crt.pem
1372        TLS_DATA_OGADMSRV_CERTFILE=$WORKDIR/opengnsys/user-certs/ogAdmSrv.crt.pem
1373        TLS_DATA_OGADMSRV_KEYFILE=$WORKDIR/opengnsys/user-certs/ogAdmSrv.key.pem
1374        TLS_DATA_WEBCONSOLE_CERTFILE=$WORKDIR/opengnsys/user-certs/WebConsole.crt.pem
1375        TLS_DATA_WEBCONSOLE_KEYFILE=$WORKDIR/opengnsys/user-certs/WebConsole.key.pem
1376
1377        ## el usuario tiene que facilitar todos los certificados
1378        ## 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
1379        if [ ! -f $TLS_DATA_OGADMSRV_CERTFILE   ]; then errorAndLog "ogAdmSrv certificate not found";   ERRORS=1; fi
1380        if [ ! -f $TLS_DATA_OGADMSRV_KEYFILE    ]; then errorAndLog "ogAdmSrv privkey not found";       ERRORS=1; fi
1381        if [ ! -f $TLS_DATA_WEBCONSOLE_CERTFILE ]; then errorAndLog "WebConsole certificate not found"; ERRORS=1; fi
1382        if [ ! -f $TLS_DATA_WEBCONSOLE_KEYFILE  ]; then errorAndLog "WebConsole privkey not found";     ERRORS=1; fi
1383
1384        if [ $ERRORS -eq 0 ]; then
1385            ## validar que las privkeys no tengan contraseña para que opengnsys pueda arrancar de forma desatendida
1386            if ! openssl rsa -in $TLS_DATA_OGADMSRV_KEYFILE   -passin pass:42 -noout; then errorAndLog "ogAdmSrv privkey is encrypted";   ERRORS=1; fi
1387            if ! openssl rsa -in $TLS_DATA_WEBCONSOLE_KEYFILE -passin pass:42 -noout; then errorAndLog "WebConsole privkey is encrypted"; ERRORS=1; fi
1388
1389            if [ $ERRORS -eq 0 ]; then
1390                # obtener los subject de cada certificado
1391                # la salida de openssl es tal que "subject=C = ES, ST = Madrid, L = Madrid, CN = test.example.org"
1392                # con el sed cocinamos la salida
1393                # además añadimos un / al principio para que el CN final sea correcto: "/C=ES/ST=Madrid/L=Madrid/CN=test.opengnsys.local"
1394                TLS_DATA_CA_SUBJ=/$(        openssl x509 -in $TLS_DATA_CA_CERTFILE         -subject -noout |sed 's/^subject=//; s/ *//g; s/,/\//g')
1395                TLS_DATA_OGADMSRV_SUBJ=/$(  openssl x509 -in $TLS_DATA_OGADMSRV_CERTFILE   -subject -noout |sed 's/^subject=//; s/ *//g; s/,/\//g')
1396                TLS_DATA_WEBCONSOLE_SUBJ=/$(openssl x509 -in $TLS_DATA_WEBCONSOLE_CERTFILE -subject -noout |sed 's/^subject=//; s/ *//g; s/,/\//g')
1397
1398                # obtener CN a partir del subject
1399                TLS_DATA_CA_CN=$(         echo $TLS_DATA_CA_SUBJ         |sed 's/.*CN=\([^/$]*\).*/\1/')
1400                TLS_DATA_OGADMSRV_CN=$(   echo $TLS_DATA_OGADMSRV_SUBJ   |sed 's/.*CN=\([^/$]*\).*/\1/')
1401                TLS_DATA_WEBCONSOLE_CN=$( echo $TLS_DATA_WEBCONSOLE_SUBJ |sed 's/.*CN=\([^/$]*\).*/\1/')
1402
1403                # los CN de los componentes que aceptan conexiones deberían resolver a una IP
1404                if ! nslookup $TLS_DATA_OGADMSRV_CN &>/dev/null; then errorAndLog "ogAdmSrv CN doesn't resolve to an IP"; ERRORS=1; fi
1405
1406                if [ $ERRORS -eq 0 ]; then
1407                    echoAndLog "Provided CA and certs are ok"
1408                fi
1409            fi
1410        fi
1411    fi
1412
1413    ## aquí también hay que tener en cuenta el sitio adicional para los user-certs
1414    if [ ! -f $WORKDIR/opengnsys/user-certs/ca.crt.pem -o $ERRORS -eq 1 ]; then
1415        echoAndLog "CA and certs not provided by the user or issues found, we will generate a new CA and all certs"
1416
1417        TLS_DATA_CA_CN=ca.opengnsys.local
1418        TLS_DATA_CA_SUBJ=/CN=ca.opengnsys.local
1419        TLS_DATA_CA_CERTFILE=$CA_DIR/certs/ca.crt.pem
1420        TLS_DATA_CA_EXPIRY=7300           # this variable is used later to make some decisions
1421
1422        TLS_DATA_OGADMSRV_CN=ogAdmSrv.opengnsys.local
1423        TLS_DATA_OGADMSRV_SUBJ=/CN=ogAdmSrv.opengnsys.local
1424        TLS_DATA_OGADMSRV_CERTFILE=$CA_DIR/certs/ogAdmSrv.crt.pem
1425        TLS_DATA_OGADMSRV_KEYFILE=$CA_DIR/private/ogAdmSrv.key.pem
1426        TLS_DATA_OGADMSRV_EXPIRY=375
1427
1428        TLS_DATA_WEBCONSOLE_CN=WebConsole.opengnsys.local
1429        TLS_DATA_WEBCONSOLE_SUBJ=/CN=WebConsole.opengnsys.local
1430        TLS_DATA_WEBCONSOLE_CERTFILE=$CA_DIR/certs/WebConsole.crt.pem
1431        TLS_DATA_WEBCONSOLE_KEYFILE=$CA_DIR/private/WebConsole.key.pem
1432        TLS_DATA_WEBCONSOLE_EXPIRY=375
1433    fi
1434
1435    # otras cosas de TLS no cubiertas arriba por no estar relacionadas con los certificados
1436    TLS_DATA_OGADMSRV_LISTEN_PORT=48888
1437
1438    return 0
1439}
1440
1441function _genCA ()
1442{
1443    SUBJ=$1
1444    EXPIRY_DAYS=$2
1445    openssl genrsa -out private/ca.key.pem 4096
1446    openssl req -config openssl.cnf -key private/ca.key.pem -new -x509 -days $EXPIRY_DAYS -sha256 -subj $SUBJ -out certs/ca.crt.pem
1447
1448    return 0
1449}
1450
1451function _genCert ()
1452{
1453    COMPONENT=$1
1454    SUBJ=$2
1455    EXPIRY_DAYS=$3
1456
1457    openssl genrsa -out private/$COMPONENT.key.pem 2048
1458    openssl req -config openssl.cnf -key private/$COMPONENT.key.pem -new -sha256 -subj $SUBJ -out csr/$COMPONENT.csr.pem
1459    openssl ca -config openssl.cnf -batch -days $EXPIRY_DAYS -notext -md sha256 -in csr/$COMPONENT.csr.pem -out certs/$COMPONENT.crt.pem
1460
1461    return 0
1462}
1463
1464function genAllCerts ()
1465{
1466    mkdir -p $CA_DIR
1467    pushd $CA_DIR
1468    cat >openssl.cnf <<EOF
1469[ca]
1470default_ca = CA_default
1471
1472[CA_default]
1473dir                    = $CA_DIR
1474certs                  = $CA_DIR/certs
1475new_certs_dir          = $CA_DIR/newcerts
1476database               = $CA_DIR/index.txt
1477serial                 = $CA_DIR/serial
1478default_md             = sha256
1479policy                 = policy_loose
1480
1481private_key            = $CA_DIR/private/ca.key.pem
1482certificate            = $CA_DIR/certs/ca.crt.pem
1483
1484[policy_loose]
1485countryName            = optional
1486stateOrProvinceName    = optional
1487localityName           = optional
1488organizationName       = optional
1489organizationalUnitName = optional
1490commonName             = supplied
1491emailAddress           = optional
1492
1493[req]
1494default_bits           = 2048
1495distinguished_name     = req_distinguished_name
1496default_md             = sha256
1497
1498[req_distinguished_name]
1499countryName            = Country Name (2 letter code)
1500EOF
1501    mkdir certs csr newcerts private
1502    chmod 0700 private
1503    touch index.txt index.txt.attr
1504    echo 1000 >serial
1505
1506    _genCA              $TLS_DATA_CA_SUBJ         $TLS_DATA_CA_EXPIRY
1507    _genCert ogAdmSrv   $TLS_DATA_OGADMSRV_SUBJ   $TLS_DATA_OGADMSRV_EXPIRY
1508    _genCert WebConsole $TLS_DATA_WEBCONSOLE_SUBJ $TLS_DATA_WEBCONSOLE_EXPIRY
1509
1510    popd
1511    return 0
1512}
1513
1514function installAllCerts ()
1515{
1516    mkdir -p $OG_BASEDIR/etc/ssl
1517
1518    ## CA cert goes to the OS store
1519    cp $TLS_DATA_CA_CERTFILE $LOCAL_CERTS_DIR/opengnsys-ca.crt
1520
1521    ## ogAdmSrv cert & key go to the application store
1522    cp $TLS_DATA_OGADMSRV_CERTFILE $TLS_DATA_OGADMSRV_KEYFILE $OG_BASEDIR/etc/ssl/
1523    ## certs of ogAdmSrv clients go to the OS store (stunnel seems to require this)
1524    cp $TLS_DATA_WEBCONSOLE_CERTFILE $LOCAL_CERTS_DIR/opengnsys-WebConsole.crt
1525
1526    ## WebConsole cert & key go to the application store
1527    cp $TLS_DATA_WEBCONSOLE_CERTFILE $TLS_DATA_WEBCONSOLE_KEYFILE $OG_BASEDIR/etc/ssl/
1528
1529    $UPDATE_CA_CMD
1530    chgrp stunnel4 $OG_BASEDIR/etc/ssl/*
1531
1532    return 0
1533}
1534
1535# si generamos nuestros propios certificados, los CNs tienen que resolver a alguna IP
1536# no podemos dar por hecho que algún servidor DNS por ahí fuera resuelva los CNs que hemos generado al instalar
1537function makeCommonNamesResolvable ()
1538{
1539    # ogAdmSrv
1540        local i=0
1541        for dev in ${DEVICE[*]}; do
1542            echoAndLog "${FUNCNAME}(): evaluating dev (${DEVICE[i]}) against defaultdev ($DEFAULTDEV)"
1543                if [ "${DEVICE[i]}" == "$DEFAULTDEV" ]; then
1544            ETC_HOSTS_IP=${SERVERIP[i]}
1545                echoAndLog "${FUNCNAME}(): will use dev (${DEVICE[i]}) IP ($ETC_HOSTS_IP)"
1546            break
1547                fi
1548                let i++
1549        done
1550
1551    if [ -z $ETC_HOSTS_IP ]; then
1552            echoAndLog "${FUNCNAME}(): Don't know what IP address to add to /etc/hosts for ogAdmSrv"
1553    else
1554        echo "$ETC_HOSTS_IP  $TLS_DATA_OGADMSRV_CN" >>/etc/hosts
1555    fi
1556
1557    return 0
1558}
1559
1560function configureStunnel ()
1561{
1562        local i=0
1563        for dev in ${DEVICE[*]}; do
1564            echoAndLog "${FUNCNAME}(): evaluating dev (${DEVICE[i]}) against defaultdev ($DEFAULTDEV)"
1565                if [ "${DEVICE[i]}" == "$DEFAULTDEV" ]; then
1566            LISTEN_IP=${SERVERIP[i]}
1567                echoAndLog "${FUNCNAME}(): will use dev (${DEVICE[i]}) IP ($LISTEN_IP)"
1568            break
1569                fi
1570                let i++
1571        done
1572
1573    if [ -z $LISTEN_IP ]; then
1574            echoAndLog "${FUNCNAME}(): Don't know what IP address to listen on"
1575        return 1
1576    fi
1577
1578    cat >/etc/stunnel/ogAdmSrv.conf <<EOF
1579setuid = stunnel4
1580setgid = stunnel4
1581pid = /var/run/stunnel4/ogAdmSrv.pid
1582
1583[ogAdmSrv]
1584accept = $LISTEN_IP:$TLS_DATA_OGADMSRV_LISTEN_PORT
1585connect = 127.0.0.1:8888
1586cert = $OG_BASEDIR/etc/ssl/ogAdmSrv.crt.pem
1587key = $OG_BASEDIR/etc/ssl/ogAdmSrv.key.pem
1588capath = $STUNNEL_CAPATH
1589requireCert = yes
1590verifyPeer = yes
1591verifyChain = yes
1592EOF
1593
1594    sed -i -e '/^ENABLED=/s/0/1/' /etc/default/stunnel4
1595    service=stunnel4
1596    $STARTSERVICE
1597    return 0
1598}
1599
1600
1601####################################################################
1602### Funciones de compilación de código fuente de servicios
1603####################################################################
1604
1605# Compilar los servicios de OpenGnsys
1606function servicesCompilation ()
1607{
1608        local hayErrores=0
1609
1610        # Compilar OpenGnsys Server
1611        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Server"
1612        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
1613        make && mv ogAdmServer $INSTALL_TARGET/sbin
1614        if [ $? -ne 0 ]; then
1615                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Server"
1616                hayErrores=1
1617        fi
1618        popd
1619        # Compilar OpenGnsys Agent
1620        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Agent"
1621        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
1622        make && mv ogAdmAgent $INSTALL_TARGET/sbin
1623        if [ $? -ne 0 ]; then
1624                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Agent"
1625                hayErrores=1
1626        fi
1627        popd
1628        # Compilar OpenGnsys Client
1629        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Client"
1630        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
1631        make && mv ogAdmClient ../../../../client/shared/bin
1632        if [ $? -ne 0 ]; then
1633                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Client"
1634                hayErrores=1
1635        fi
1636        popd
1637
1638        return $hayErrores
1639}
1640
1641####################################################################
1642### Funciones de copia de la Interface de administración
1643####################################################################
1644
1645# Copiar carpeta de Interface
1646function copyInterfaceAdm ()
1647{
1648        local hayErrores=0
1649
1650        # Crear carpeta y copiar Interface
1651        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
1652        cp -ar $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client/interfaceAdm
1653        if [ $? -ne 0 ]; then
1654                echoAndLog "${FUNCNAME}(): error while copying Administration Interface Folder"
1655                hayErrores=1
1656        fi
1657
1658        return $hayErrores
1659}
1660
1661
1662####################################################################
1663### Funciones instalacion cliente opengnsys
1664####################################################################
1665
1666function copyClientFiles()
1667{
1668        local errstatus=0
1669
1670        echoAndLog "${FUNCNAME}(): Copying OpenGnsys Client files."
1671        cp -a $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
1672        if [ $? -ne 0 ]; then
1673                errorAndLog "${FUNCNAME}(): error while copying client estructure"
1674                errstatus=1
1675        fi
1676
1677        echoAndLog "${FUNCNAME}(): Copying OpenGnsys Cloning Engine files."
1678        mkdir -p $INSTALL_TARGET/client/lib/engine/bin
1679        cp -a $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
1680        if [ $? -ne 0 ]; then
1681                errorAndLog "${FUNCNAME}(): error while copying engine files"
1682                errstatus=1
1683        fi
1684
1685        if [ $errstatus -eq 0 ]; then
1686                echoAndLog "${FUNCNAME}(): client copy files success."
1687        else
1688                errorAndLog "${FUNCNAME}(): client copy files with errors"
1689        fi
1690
1691        return $errstatus
1692}
1693
1694
1695# Crear certificados para la firma de cargadores de arranque.
1696function createCerts ()
1697{
1698        local SSLCFGDIR=$INSTALL_TARGET/client/etc/ssl
1699        echoAndLog "${FUNCNAME}(): creating certificate files"
1700        mkdir -p $SSLCFGDIR/{certs,private}
1701        openssl req -new -x509 -newkey rsa:2048 -keyout $SSLCFGDIR/private/opengnsys.key -out $SSLCFGDIR/certs/opengnsys.crt -nodes -days 3650 -subj "/CN=OpenGnsys/"
1702        openssl x509 -in $SSLCFGDIR/certs/opengnsys.crt -out $SSLCFGDIR/certs/opengnsys.cer -outform DER
1703        echoAndLog "${FUNCNAME}(): certificate successfully created"
1704}
1705
1706
1707# Crear cliente OpenGnsys.
1708function clientCreate()
1709{
1710        if [ $# -ne 1 ]; then
1711                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1712                exit 1
1713        fi
1714
1715        local FILENAME="$1"
1716        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
1717
1718        # Descargar cliente, si es necesario.
1719        if [ -s $PROGRAMDIR/$FILENAME ]; then
1720                echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
1721                mv $PROGRAMDIR/$FILENAME $TARGETFILE
1722        else
1723                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
1724                oglivecli download $FILENAME
1725        fi
1726        if [ ! -s $TARGETFILE ]; then
1727                errorAndLog "${FUNCNAME}(): Error loading $FILENAME"
1728                return 1
1729        fi
1730
1731        # Montar imagen, copiar cliente ogclient y desmontar.
1732        echoAndLog "${FUNCNAME}(): Installing ogLive Client"
1733        echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | \
1734                        oglivecli install $FILENAME
1735
1736        echoAndLog "${FUNCNAME}(): Client generation success"
1737}
1738
1739
1740# Configuración básica de servicios de OpenGnsys
1741function openGnsysConfigure()
1742{
1743        local i=0
1744        local dev=""
1745        local CONSOLEURL
1746
1747        echoAndLog "${FUNCNAME}(): Copying init files."
1748        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
1749        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default /etc/default/opengnsys
1750        # Deshabilitar servicios de BitTorrent si no están instalados.
1751        if [ ! -e /usr/bin/bttrack ]; then
1752                sed -i 's/RUN_BTTRACKER="yes"/RUN_BTTRACKER="no"/; s/RUN_BTSEEDER="yes"/RUN_BTSEEDER="no"/' \
1753                        /etc/default/opengnsys
1754        fi
1755        echoAndLog "${FUNCNAME}(): Creating cron files."
1756        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
1757        echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
1758        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
1759        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/ogagentqueue.cron ] && $INSTALL_TARGET/bin/ogagentqueue.cron" > /etc/cron.d/ogagentqueue
1760
1761        echoAndLog "${FUNCNAME}(): Creating logrotate configuration files."
1762        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1763                $WORKDIR/opengnsys/server/etc/logrotate.tmpl > /etc/logrotate.d/opengnsysServer
1764
1765        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1766                $WORKDIR/opengnsys/repoman/etc/logrotate.tmpl > /etc/logrotate.d/opengnsysRepo
1767
1768        echoAndLog "${FUNCNAME}(): Creating OpenGnsys config files."
1769        for dev in ${DEVICE[*]}; do
1770                if [ -n "${SERVERIP[i]}" ]; then
1771                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1772                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1773                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1774                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1775                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer/ogAdmServer.cfg > $INSTALL_TARGET/etc/ogAdmServer-$dev.cfg
1776                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1777                                $WORKDIR/opengnsys/repoman/etc/ogAdmRepo.cfg.tmpl > $INSTALL_TARGET/etc/ogAdmRepo-$dev.cfg
1778                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1779                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1780                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1781                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1782                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent/ogAdmAgent.cfg > $INSTALL_TARGET/etc/ogAdmAgent-$dev.cfg
1783                        CONSOLEURL="https://${SERVERIP[i]}/opengnsys"
1784                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1785                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1786                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1787                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1788                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
1789                                $INSTALL_TARGET/www/controlacceso.php > $INSTALL_TARGET/www/controlacceso-$dev.php
1790                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1791                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
1792                                $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient/ogAdmClient.cfg > $INSTALL_TARGET/client/etc/ogAdmClient-$dev.cfg
1793                        if [ "$dev" == "$DEFAULTDEV" ]; then
1794                                OPENGNSYS_CONSOLEURL="$CONSOLEURL"
1795                        fi
1796                fi
1797                let i++
1798        done
1799        ln -f $INSTALL_TARGET/etc/ogAdmServer-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmServer.cfg
1800        ln -f $INSTALL_TARGET/etc/ogAdmRepo-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmRepo.cfg
1801        ln -f $INSTALL_TARGET/etc/ogAdmAgent-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmAgent.cfg
1802        ln -f $INSTALL_TARGET/client/etc/ogAdmClient-$DEFAULTDEV.cfg $INSTALL_TARGET/client/etc/ogAdmClient.cfg
1803        ln -f $INSTALL_TARGET/www/controlacceso-$DEFAULTDEV.php $INSTALL_TARGET/www/controlacceso.php
1804
1805        # Configuración del motor de clonación.
1806        # - Zona horaria del servidor.
1807        TZ=$(timedatectl status|awk -F"[:()]" '/Time.*zone/ {print $2}')
1808        cat << EOT >> $INSTALL_TARGET/client/etc/engine.cfg
1809# OpenGnsys Server timezone.
1810TZ="${TZ// /}"
1811EOT
1812
1813        # Revisar permisos generales.
1814        if [ -x $INSTALL_TARGET/bin/checkperms ]; then
1815                echoAndLog "${FUNCNAME}(): Checking permissions."
1816                OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENT_USER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" checkperms
1817        fi
1818
1819        # Evitar inicio de duplicado en Ubuntu 14.04 (Upstart y SysV Init).
1820        if [ -f /etc/init/${MYSQLSERV}.conf -a -n "$(which initctl 2>/dev/null)" ]; then
1821                service=$MYSQLSERV
1822                $DISABLESERVICE
1823        fi
1824
1825        # Actualizar tokens de autenticación e iniciar los servicios.
1826        service="opengnsys"
1827        $ENABLESERVICE
1828        if [ -x $INSTALL_TARGET/bin/settoken ]; then
1829                echoAndLog "${FUNCNAME}(): Setting authentication tokens and starting OpenGnsys services."
1830                $INSTALL_TARGET/bin/settoken "$OPENGNSYS_DB_USER"
1831                $INSTALL_TARGET/bin/settoken -f
1832        else
1833                echoAndLog "${FUNCNAME}(): Starting OpenGnsys services."
1834                $STARTSERVICE
1835        fi
1836}
1837
1838
1839#####################################################################
1840#######  Función de resumen informativo de la instalación
1841#####################################################################
1842
1843function installationSummary()
1844{
1845        local VERSIONFILE REVISION
1846
1847        # Crear fichero de versión y revisión, si no existe.
1848        VERSIONFILE="$INSTALL_TARGET/doc/VERSION.json"
1849        [ -f $VERSIONFILE ] || echo '{ "project": "OpenGnsys" }' >$VERSIONFILE
1850        # Incluir datos de revisión, si se está instalando desde el repositorio
1851        # de código o si no está incluida en el fichero de versión.
1852        if [ $REMOTE -eq 1 ] || [ -z "$(jq -r '.release' $VERSIONFILE)" ]; then
1853                # Revisión: rAñoMesDía.Gitcommit (8 caracteres de fecha y 7 primeros de commit).
1854                RELEASE=$(curl -s "$API_URL/branches/$BRANCH" | jq -r '"r" + (.commit.commit.committer.date | split("-") | join("")[:8]) + "." + (.commit.sha[:7])' 2>/dev/null)
1855                # Obtener revisión para etiqueta de versión en vez de rama de código.
1856                [ -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)
1857                jq ".release=\"$RELEASE\"" $VERSIONFILE | sponge $VERSIONFILE
1858        fi
1859        VERSION="$(jq -r '[.project, .version, .codename, .release] | join(" ")' $VERSIONFILE 2>/dev/null)"
1860
1861        # Mostrar información.
1862        echo
1863        echoAndLog "OpenGnsys Installation Summary"
1864        echo       "=============================="
1865        echoAndLog "Project version:                  $VERSION"
1866        echoAndLog "Installation directory:           $INSTALL_TARGET"
1867        echoAndLog "Installation log file:            $LOG_FILE"
1868        echoAndLog "Repository directory:             $INSTALL_TARGET/images"
1869        echoAndLog "DHCP configuration directory:     $DHCPCFGDIR"
1870        echoAndLog "TFTP configuration directory:     $TFTPCFGDIR"
1871        echoAndLog "Installed ogLive client:          $(oglivecli list | awk '{print $2}')"
1872        echoAndLog "Samba configuration directory:    $SAMBACFGDIR"
1873        echoAndLog "Web Console URL:                  $OPENGNSYS_CONSOLEURL"
1874        echoAndLog "Web Console access data:          entered by the user"
1875        if grep -q "^RUN_BTTRACK.*no" /etc/default/opengnsys; then
1876                echoAndLog "BitTorrent service is disabled."
1877        fi
1878        echo
1879        echoAndLog "Post-Installation Instructions:"
1880        echo       "==============================="
1881        echoAndLog "You can improve server security by configuring firewall and SELinux,"
1882        echoAndLog "   running \"$INSTALL_TARGET/lib/security-config\" script as root."
1883        echoAndLog "It's strongly recommended to synchronize this server with an NTP server."
1884        echoAndLog "Review or edit all configuration files."
1885        echoAndLog "Insert DHCP configuration data and restart service."
1886        echoAndLog "Optional: If you want to use BURG as boot manager, run"
1887        echoAndLog "   \"curl $DOWNLOADURL/burg.tgz -o $INSTALL_TARGET/client/lib/burg.tgz\" as root."
1888        echoAndLog "Optional: Log-in as Web Console admin user."
1889        echoAndLog " - Review default Organization data and assign access to users."
1890        echoAndLog "Log-in as Web Console organization user."
1891        echoAndLog " - Insert OpenGnsys data (labs, computers, menus, etc)."
1892echo
1893}
1894
1895
1896
1897#####################################################################
1898####### Proceso de instalación de OpenGnsys
1899#####################################################################
1900
1901# Sólo ejecutable por usuario root
1902if [ "$(whoami)" != 'root' ]; then
1903        echo "ERROR: this program must run under root privileges!!"
1904        exit 1
1905fi
1906
1907globalSetup $MY_BRANCH
1908# Comprobar instalación previa.
1909if cat $INSTALL_TARGET/doc/VERSION.* &>/dev/null; then
1910        echo "ERROR: OpenGnsys is already installed. Run \"$INSTALL_TARGET/lib/opengnsys_update.sh\" as root to update."
1911        exit 2
1912fi
1913
1914echoAndLog "OpenGnsys installation begins at $(date)"
1915# Introducir datos de configuración y establecer variables globales.
1916userData
1917
1918mkdir -p $WORKDIR
1919pushd $WORKDIR
1920
1921# Detectar datos iniciales de auto-configuración del instalador.
1922autoConfigure
1923
1924# Detectar parámetros de red y comprobar si hay conexión.
1925getNetworkSettings
1926if [ $? -ne 0 ]; then
1927        errorAndLog "Error reading default network settings."
1928        exit 1
1929fi
1930checkNetworkConnection
1931if [ $? -ne 0 ]; then
1932        errorAndLog "Error connecting to server. Causes:"
1933        errorAndLog " - Network is unreachable, review devices parameters."
1934        errorAndLog " - You are inside a private network, configure the proxy service."
1935        errorAndLog " - Server is temporally down, try agian later."
1936        exit 1
1937fi
1938
1939# Detener servicios de OpenGnsys, si están activos previamente.
1940[ -f /etc/init.d/opengnsys ] && /etc/init.d/opengnsys stop
1941
1942# Actualizar repositorios
1943updatePackageList
1944
1945# Instalación de dependencias (paquetes de sistema operativo).
1946declare -a notinstalled
1947checkDependencies DEPENDENCIES notinstalled
1948if [ $? -ne 0 ]; then
1949        installDependencies notinstalled
1950        if [ $? -ne 0 ]; then
1951                echoAndLog "Error while installing some dependeces, please verify your server installation before continue"
1952                exit 1
1953        fi
1954fi
1955if [ -n "$INSTALLEXTRADEPS" ]; then
1956        echoAndLog "Installing extra dependencies"
1957        for (( i=0; i<${#INSTALLEXTRADEPS[*]}; i++ )); do
1958                eval ${INSTALLEXTRADEPS[i]}
1959        done
1960fi
1961
1962# Detectar datos de auto-configuración después de instalar paquetes.
1963autoConfigurePost
1964
1965# Arbol de directorios de OpenGnsys.
1966createDirs ${INSTALL_TARGET}
1967if [ $? -ne 0 ]; then
1968        errorAndLog "Error while creating directory paths!"
1969        exit 1
1970fi
1971
1972# Si es necesario, descarga el repositorio de código en directorio temporal
1973if [ $REMOTE -eq 1 ]; then
1974        downloadCode $GIT_REPO
1975        if [ $? -ne 0 ]; then
1976                errorAndLog "Error while getting code from the repository"
1977                exit 1
1978        fi
1979else
1980        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
1981fi
1982
1983# TLS
1984gatherCertsInfo
1985if [ $? -ne 0 ]; then
1986        errorAndLog 'Not all required certificates have been provided, or privkey or DNS issues'
1987        exit 1
1988fi
1989[ $TLS_DATA_CA_EXPIRY ] && genAllCerts                  ## el usuario no nos ha dado sus certificados: generamos unos
1990installAllCerts
1991[ $TLS_DATA_CA_EXPIRY ] && makeCommonNamesResolvable    ## el usuario no nos ha dado sus certificados: configuramos resolución de nombres en /etc/hosts
1992configureStunnel
1993if [ $? -ne 0 ]; then
1994        errorAndLog 'Error while setting stunnel up'
1995        exit 1
1996fi
1997
1998# Compilar código fuente de los servicios de OpenGnsys.
1999servicesCompilation
2000if [ $? -ne 0 ]; then
2001        errorAndLog "Error while compiling OpenGnsys services"
2002        exit 1
2003fi
2004
2005# Copiar carpeta Interface entre administración y motor de clonación.
2006copyInterfaceAdm
2007if [ $? -ne 0 ]; then
2008        errorAndLog "Error while copying Administration Interface"
2009        exit 1
2010fi
2011
2012# Configuración de TFTP.
2013tftpConfigure
2014
2015# Configuración de Samba.
2016smbConfigure
2017if [ $? -ne 0 ]; then
2018        errorAndLog "Error while configuring Samba server!"
2019        exit 1
2020fi
2021
2022# Configuración de Rsync.
2023rsyncConfigure
2024
2025# Configuración ejemplo DHCP.
2026dhcpConfigure
2027if [ $? -ne 0 ]; then
2028        errorAndLog "Error while copying your dhcp server files!"
2029        exit 1
2030fi
2031
2032# Copiar ficheros de servicios OpenGnsys Server.
2033copyServerFiles ${INSTALL_TARGET}
2034if [ $? -ne 0 ]; then
2035        errorAndLog "Error while copying the server files!"
2036        exit 1
2037fi
2038INSTVERSION=$(jq -r '.version' $INSTALL_TARGET/doc/VERSION.json)
2039
2040# Instalar base de datos de OpenGnsys Admin.
2041isInArray notinstalled "mysql-server" || isInArray notinstalled "mariadb-server"
2042if [ $? -eq 0 ]; then
2043        # Enable database manager (MySQL, if missing, MariaDB).
2044        service=$MYSQLSERV
2045        $ENABLESERVICE
2046        if [ $? != 0 ]; then
2047                service=$MARIADBSERV
2048                $ENABLESERVICE
2049        fi
2050        # Start database manager.
2051        $STARTSERVICE
2052        # Asignar clave del usuario "root".
2053        mysqlSetRootPassword "${MYSQL_ROOT_PASSWORD}"
2054else
2055        # Si ya está instalado el gestor de bases de datos, obtener clave de "root".
2056        mysqlGetRootPassword
2057fi
2058
2059# Copy MySQL configuration template
2060cp $WORKDIR/opengnsys/server/etc/mysqld-og.cnf $MYSQLCFGDIR 2>/dev/null
2061# Restart database manager.
2062$STARTSERVICE
2063
2064mysqlTestConnection "${MYSQL_ROOT_PASSWORD}"
2065if [ $? -ne 0 ]; then
2066        errorAndLog "Error while connection to mysql"
2067        exit 1
2068fi
2069mysqlDbExists ${OPENGNSYS_DATABASE}
2070if [ $? -ne 0 ]; then
2071        echoAndLog "Creating Web Console database"
2072        mysqlCreateDb ${OPENGNSYS_DATABASE}
2073        if [ $? -ne 0 ]; then
2074                errorAndLog "Error while creating Web Console database"
2075                exit 1
2076        fi
2077else
2078        echoAndLog "Web Console database exists, ommiting creation"
2079fi
2080
2081mysqlCheckUserExists ${OPENGNSYS_DB_USER}
2082if [ $? -ne 0 ]; then
2083        echoAndLog "Creating user in database"
2084        mysqlCreateAdminUserToDb ${OPENGNSYS_DATABASE} ${OPENGNSYS_DB_USER} "${OPENGNSYS_DB_PASSWD}"
2085        if [ $? -ne 0 ]; then
2086                errorAndLog "Error while creating database user"
2087                exit 1
2088        fi
2089
2090fi
2091
2092mysqlCheckDbIsEmpty ${OPENGNSYS_DATABASE}
2093if [ $? -eq 0 ]; then
2094        echoAndLog "Creating tables..."
2095        if [ -f $WORKDIR/$OPENGNSYS_DB_CREATION_FILE ]; then
2096                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_CREATION_FILE
2097        else
2098                errorAndLog "Unable to locate $WORKDIR/$OPENGNSYS_DB_CREATION_FILE!!"
2099                exit 1
2100        fi
2101else
2102        # Si existe fichero ogBDAdmin-VersLocal-VersRepo.sql; aplicar cambios.
2103        REPOVERSION=$(jq -r '.version' $WORKDIR/opengnsys/doc/VERSION.json)
2104        OPENGNSYS_DB_UPDATE_FILE="opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
2105        if [ -f $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE ]; then
2106                echoAndLog "Updating tables from version $INSTVERSION to $REPOVERSION"
2107                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE
2108        else
2109                echoAndLog "Database unchanged."
2110        fi
2111fi
2112# Eliminar fichero temporal con credenciales de acceso a MySQL.
2113rm -f $TMPMYCNF
2114
2115# Copiando páqinas web.
2116installWebFiles
2117# Configurar variables de PHP
2118configurePHPvars $TLS_DATA_OGADMSRV_CN $TLS_DATA_OGADMSRV_LISTEN_PORT
2119# Descargar/descomprimir archivos descargables.
2120installDownloadableFiles
2121# Generar páqinas web de documentación de la API
2122makeDoxygenFiles
2123
2124# Creando configuración de Apache.
2125installWebConsoleApacheConf $INSTALL_TARGET $APACHECFGDIR
2126if [ $? -ne 0 ]; then
2127        errorAndLog "Error configuring Apache for OpenGnsys Admin"
2128        exit 1
2129fi
2130
2131popd
2132
2133# Crear la estructura de los accesos al servidor desde el cliente (shared)
2134copyClientFiles
2135if [ $? -ne 0 ]; then
2136        errorAndLog "Error creating client structure"
2137fi
2138
2139# Crear certificado para firmar cargadores
2140createCerts
2141
2142# Crear la estructura del cliente de OpenGnsys.
2143for i in $OGLIVE; do
2144        if ! clientCreate "$i"; then
2145                errorAndLog "Error creating client $i"
2146                exit 1
2147        fi
2148done
2149
2150# Configuración de servicios de OpenGnsys
2151openGnsysConfigure
2152
2153# Mostrar sumario de la instalación e instrucciones de post-instalación.
2154installationSummary
2155
2156rm -rf $WORKDIR
2157echoAndLog "OpenGnsys installation finished at $(date)"
2158exit 0
2159
Note: See TracBrowser for help on using the repository browser.