source: installer/opengnsys_installer.sh @ 4d78df3

Last change on this file since 4d78df3 was c3648b9, checked in by Irina Gómez <irinagomez@…>, 4 years ago

#1026 The installation script displays information message only when distribution is different than advised.

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