source: installer/opengnsys_installer.sh

qndtest
Last change on this file was df0cd09, checked in by Ramón M. Gómez <ramongomez@…>, 19 months ago

#1078: Installation script now runs on Ubuntu 22.04

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