source: installer/opengnsys_update.sh @ 5d05b06

Last change on this file since 5d05b06 was e7ffae8, checked in by OpenGnSys Support Team <soporte-og@…>, 4 years ago

#988 Add ogserver.json creation when running opengnsys_update.sh

This patch enables the creation of a default json config for the
ogserver when running opengnsys_update.sh, if no prior json config
is detected.

Eg. when updating from 1.1.1c to 1.2.0

Reviewed-by: Jose M. Guisado <jguisado@…>

  • Property mode set to 100755
File size: 47.5 KB
Line 
1#!/bin/bash
2#/**
3#@file    opengnsys_update.sh
4#@brief   Script actualización de OpenGnsys
5#@version 0.9 - basado en opengnsys_installer.sh
6#@author  Ramón Gómez - ETSII Univ. Sevilla
7#@date    2010/01/27
8#@version 1.0 - adaptación a OpenGnSys 1.0
9#@author  Ramón Gómez - ETSII Univ. Sevilla
10#@date    2011/03/02
11#@version 1.0.1 - control de auto actualización del script
12#@author  Ramón Gómez - ETSII Univ. Sevilla
13#@date    2011/05/17
14#@version 1.0.2a - obtiene valor de dirección IP por defecto
15#@author  Ramón Gómez - ETSII Univ. Sevilla
16#@date    2012/01/18
17#@version 1.0.3 - Compatibilidad con Debian y auto configuración de acceso a BD.
18#@author  Ramón Gómez - ETSII Univ. Sevilla
19#@date    2012/03/12
20#@version 1.0.4 - Detector de distribución y compatibilidad con CentOS.
21#@author  Ramón Gómez - ETSII Univ. Sevilla
22#@date    2012/05/04
23#@version 1.0.5 - Actualizar BD en la misma versión, compatibilidad con Fedora (systemd) y configuración de Rsync.
24#@author  Ramón Gómez - ETSII Univ. Sevilla
25#@date    2014/04/03
26#@version 1.0.6 - Redefinir URLs de ficheros de configuración usando HTTPS.
27#@author  Ramón Gómez - ETSII Univ. Sevilla
28#@date    2015/03/12
29#@version 1.1.0 - Instalación de API REST y configuración de zona horaria.
30#@author  Ramón Gómez - ETSII Univ. Sevilla
31#@date    2015/11/09
32#@version 1.1.1a - Elegir versión a actualizar.
33#@author  Ramón Gómez - ETSII Univ. Sevilla
34#@date    2019/12/13
35#*/
36
37
38####  AVISO: NO EDITAR variables de configuración.
39####  WARNING: DO NOT EDIT configuration variables.
40INSTALL_TARGET=/opt/opengnsys           # Directorio de instalación
41PATH=$PATH:$INSTALL_TARGET/bin
42OPENGNSYS_CLIENTUSER="opengnsys"        # Usuario Samba
43
44
45# Sólo ejecutable por usuario root
46if [ "$(whoami)" != 'root' ]; then
47        echo "ERROR: this program must run under root privileges!!"
48        exit 1
49fi
50# Error si OpenGnsys no está instalado (no existe el directorio del proyecto)
51if [ ! -d $INSTALL_TARGET ]; then
52        echo "ERROR: OpenGnsys is not installed, cannot update!!"
53        exit 1
54fi
55
56source $INSTALL_TARGET/lib/ogfunctions.sh || exit 1
57
58# Cargar configuración de acceso a la base de datos.
59if [ -r $INSTALL_TARGET/etc/ogserver.json ]; then
60        source_json_config $INSTALL_TARGET/etc/ogserver.json
61elif [ -r $INSTALL_TARGET/etc/ogserver.cfg ]; then
62        source $INSTALL_TARGET/etc/ogserver.cfg
63elif [ -r $INSTALL_TARGET/etc/ogAdmServer.cfg ]; then
64        source $INSTALL_TARGET/etc/ogAdmServer.cfg
65fi
66OPENGNSYS_DATABASE=${OPENGNSYS_DATABASE:-"$CATALOG"}            # Base de datos
67OPENGNSYS_DBUSER=${OPENGNSYS_DBUSER:-"$USUARIO"}                # Usuario de acceso
68OPENGNSYS_DBPASSWORD=${OPENGNSYS_DBPASSWORD:-"$PASSWORD"}       # Clave del usuario
69if [ -z "$OPENGNSYS_DATABASE" -o -z "$OPENGNSYS_DBUSER" -o -z "$OPENGNSYS_DBPASSWORD" ]; then
70        echo "ERROR: set OPENGNSYS_DATABASE, OPENGNSYS_DBUSER and OPENGNSYS_DBPASSWORD"
71        echo "       variables, and run this script again."
72        exit 1
73fi
74
75# Comprobar si se ha descargado el paquete comprimido (REMOTE=0) o sólo el instalador (REMOTE=1).
76PROGRAMDIR=$(readlink -e $(dirname "$0"))
77PROGRAMNAME=$(basename "$0")
78OPENGNSYS_SERVER="opengnsys.es"
79if [ -d "$PROGRAMDIR/../installer" ]; then
80        REMOTE=0
81else
82        REMOTE=1
83fi
84
85WORKDIR=/tmp/opengnsys_update
86mkdir -p $WORKDIR
87
88# Registro de incidencias.
89OGLOGFILE=$INSTALL_TARGET/log/${PROGRAMNAME%.sh}.log
90LOG_FILE=/tmp/$(basename $OGLOGFILE)
91
92
93
94#####################################################################
95####### Algunas funciones útiles de propósito general:
96#####################################################################
97
98# Generar variables de configuración del actualizador
99# Variables globales:
100# - OSDISTRIB - distribución Linux
101# - DEPENDENCIES - array de dependencias que deben estar instaladas
102# - UPDATEPKGLIST, INSTALLPKGS, CHECKPKG - comandos para gestión de paquetes
103# - APACHECFGDIR, APACHESERV, PHPFPMSERV, DHCPSERV, MYSQLSERV, MYSQLCFGDIR, INETDCFGDIR - configuración y servicios
104
105function autoConfigure()
106{
107        local service
108
109        # Detectar sistema operativo del servidor (compatible con fichero os-release y con LSB).
110        if [ -f /etc/os-release ]; then
111                source /etc/os-release
112                OSDISTRIB="$ID"
113                OSVERSION="$VERSION_ID"
114        else
115                OSDISTRIB=$(lsb_release -is 2>/dev/null)
116                OSVERSION=$(lsb_release -rs 2>/dev/null)
117        fi
118        # Convertir distribución a minúsculas y obtener solo el 1er número de versión.
119        OSDISTRIB="${OSDISTRIB,,}"
120        OSVERSION="${OSVERSION%%.*}"
121
122        # Configuración según la distribución de Linux.
123        if [ -f /etc/debian_version ]; then
124                # Distribución basada en paquetes Deb.
125                DEPENDENCIES=( curl rsync 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 php-fpm gawk libdbi-dev libdbi1 libdbd-mysql automake liblz4-tool )
126                # Paquete correcto para realpath.
127                [ -z "$(apt-cache pkgnames realpath)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//realpath/coreutils} )
128                UPDATEPKGLIST="add-apt-repository -y ppa:ondrej/php; apt-get update"
129                INSTALLPKGS="apt-get -y install"
130                DELETEPKGS="apt-get -y purge"
131                CHECKPKG="dpkg -s \$package 2>/dev/null | grep -q \"Status: install ok\""
132                if which service &>/dev/null; then
133                        STARTSERVICE="eval service \$service restart"
134                        STOPSERVICE="eval service \$service stop"
135                        SERVICESTATUS="eval service \$service status"
136                else
137                        STARTSERVICE="eval /etc/init.d/\$service restart"
138                        STOPSERVICE="eval /etc/init.d/\$service stop"
139                        SERVICESTATUS="eval /etc/init.d/\$service status"
140                fi
141                ENABLESERVICE="eval systemctl enable \$service.service"
142                APACHEENABLEMODS="ssl rewrite proxy_fcgi fastcgi actions alias"
143                APACHEDISABLEMODS="php"
144                APACHEUSER="www-data"
145                APACHEGROUP="www-data"
146                MYSQLCFGDIR=/etc/mysql/mysql.conf.d
147                MYSQLSERV="mysql"
148                PHPFPMSERV="php-fpm"
149                INETDCFGDIR=/etc/xinetd.d
150        elif [ -f /etc/redhat-release ]; then
151                # Distribución basada en paquetes rpm.
152                DEPENDENCIES=( curl rsync btrfs-progs procps-ng arp-scan 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)
153                # Repositorios para PHP 7 en CentOS.
154                [ "$OSDISTRIB" == "centos" ] && UPDATEPKGLIST="yum update -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-$OSVERSION.noarch.rpm http://rpms.remirepo.net/enterprise/remi-release-$OSVERSION.rpm"
155                INSTALLPKGS="yum install -y"
156                DELETEPKGS="yum remove -y"
157                CHECKPKG="rpm -q --quiet \$package"
158                if which systemctl &>/dev/null; then
159                        STARTSERVICE="eval systemctl restart \$service.service"
160                        STOPSERVICE="eval systemctl stop \$service.service"
161                        ENABLESERVICE="eval systemctl enable \$service.service"
162                        SERVICESTATUS="eval systemctl status \$service.service"
163                else
164                        STARTSERVICE="eval service \$service restart"
165                        STOPSERVICE="eval service \$service stop"
166                        ENABLESERVICE="eval chkconfig \$service on"
167                        SERVICESTATUS="eval service \$service status"
168                fi
169                APACHEUSER="apache"
170                APACHEGROUP="apache"
171                MYSQLCFGDIR=/etc/my.cnf.d
172                MYSQLSERV="mariadb"
173                PHPFPMSERV="php-fpm"
174                INETDCFGDIR=/etc/xinetd.d
175        else
176                # Otras distribuciones.
177                :
178        fi
179        for service in apache2 httpd; do
180                [ -d "/etc/$service" ] && APACHECFGDIR="/etc/$service"
181                if $SERVICESTATUS &>/dev/null; then APACHESERV="$service"; fi
182        done
183        for service in dhcpd dhcpd3-server isc-dhcp-server; do
184                if $SERVICESTATUS &>/dev/null; then DHCPSERV="$service"; fi
185        done
186}
187
188
189# Choose an available version to update.
190function chooseVersion()
191{
192    local RELEASES DOWNLOADS INSTVERSION INSTRELEASE RELDATE
193
194    # Development branch.
195    BRANCH="master"
196    API_URL="https://api.github.com/repos/opengnsys/OpenGnsys/branches/$BRANCH"
197
198    RELEASES=( )
199    DOWNLOADS=( )
200    # If updating from a local or very old version, use the default data.
201    if [ $REMOTE -eq 1 ] && which jq &>/dev/null && [ -f $INSTALL_TARGET/doc/VERSION.json -o -f $INSTALL_TARGET/doc/VERSION.txt ]; then
202        # Installed release.
203        [ -f $INSTALL_TARGET/doc/VERSION.json ] && read -pe INSTVERSION INSTRELEASE <<< $(jq -r '.version+" "+.release' $INSTALL_TARGET/doc/VERSION.json)
204        [ -f $INSTALL_TARGET/doc/VERSION.txt ] && read -pe INSTVERSION INSTRELEASE <<< $(awk '{print $2,$3}' $INSTALL_TARGET/doc/VERSION.txt)
205        # Fetch tags (releases) data from GitHub.
206        while read -pe TAG URL; do
207            if [[ $TAG =~ ^opengnsys- ]]; then
208                [ "${TAG#opengnsys-}" \< "${INSTVERSION%pre}" ] && continue
209                RELDATE=$(curl -s "$URL" | jq -r '.commit.committer.date | split("-") | join("")[:8]')
210                RELEASES+=( "${TAG} ($RELDATE)" )
211                DOWNLOADS+=( "$URL" )
212            fi
213        done <<< $(curl -s "$API_URL/../../tags" | jq -r '.[] | .name+" "+.commit.url')
214        # Add development (master) branch.
215        RELEASES+=( "$BRANCH" )
216        DOWNLOADS+=( "$API_URL" )
217        # Show selection menu, if needed.
218        if [ ${#RELEASES[@]} -gt 1 ]; then
219            echo "Installed version: $INSTVERSION $INSTRELEASE"
220            echo "Versions available for update (\"$BRANCH\" is the latest development branch):"
221            PS3="Enter a number (CTRL-C to exit): "
222            select opt in "${RELEASES[@]}"; do
223                if [ -n "$opt" ]; then
224                    BRANCH="${opt%% *}"
225                    API_URL="${DOWNLOADS[REPLY-1]}"
226                    break
227                fi
228            done
229        fi
230    fi
231    # Download URLs.
232    CODE_URL="https://codeload.github.com/opengnsys/OpenGnsys/zip/$BRANCH"
233    RAW_URL="https://raw.githubusercontent.com/opengnsys/OpenGnsys/$BRANCH"
234}
235
236
237# Comprobar auto-actualización.
238function checkAutoUpdate()
239{
240        local update=0
241
242        # Actaulizar el script si ha cambiado o no existe el original.
243        if [ $REMOTE -eq 1 ]; then
244                curl -s $RAW_URL/installer/$PROGRAMNAME -o $PROGRAMNAME
245                chmod +x $PROGRAMNAME
246                if ! diff -q $PROGRAMNAME $INSTALL_TARGET/lib/$PROGRAMNAME 2>/dev/null || ! test -f $INSTALL_TARGET/lib/$PROGRAMNAME; then
247                        mv $PROGRAMNAME $INSTALL_TARGET/lib
248                        update=1
249                else
250                        rm -f $PROGRAMNAME
251                fi
252        else
253                if ! diff -q $PROGRAMDIR/$PROGRAMNAME $INSTALL_TARGET/lib/$PROGRAMNAME 2>/dev/null || ! test -f $INSTALL_TARGET/lib/$PROGRAMNAME; then
254                        cp -a $PROGRAMDIR/$PROGRAMNAME $INSTALL_TARGET/lib
255                        update=1
256                fi
257        fi
258
259        return $update
260}
261
262
263function getDateTime()
264{
265        date "+%Y%m%d-%H%M%S"
266}
267
268# Escribe a fichero y muestra por pantalla
269function echoAndLog()
270{
271        echo "$1"
272        DATETIME=`getDateTime`
273        echo "$DATETIME;$SSH_CLIENT;$1" >> $LOG_FILE
274}
275
276function errorAndLog()
277{
278        echo "ERROR: $1"
279        DATETIME=`getDateTime`
280        echo "$DATETIME;$SSH_CLIENT;ERROR: $1" >> $LOG_FILE
281}
282
283# Escribe a fichero y muestra mensaje de aviso
284function warningAndLog()
285{
286        local DATETIME=`getDateTime`
287        echo "Warning: $1"
288        echo "$DATETIME;$SSH_CLIENT;Warning: $1" >> $LOG_FILE
289}
290
291
292#####################################################################
293####### Funciones de copia de seguridad y restauración de ficheros
294#####################################################################
295
296# Hace un backup del fichero pasado por parámetro
297# deja un -last y uno para el día
298function backupFile()
299{
300        if [ $# -ne 1 ]; then
301                errorAndLog "${FUNCNAME}(): invalid number of parameters"
302                exit 1
303        fi
304
305        local fichero=$1
306        local fecha=`date +%Y%m%d`
307
308        if [ ! -f $fichero ]; then
309                warningAndLog "${FUNCNAME}(): file $fichero doesn't exists"
310                return 1
311        fi
312
313        echoAndLog "${FUNCNAME}(): Making $fichero back-up"
314
315        # realiza una copia de la última configuración como last
316        cp -a $fichero "${fichero}-LAST"
317
318        # si para el día no hay backup lo hace, sino no
319        if [ ! -f "${fichero}-${fecha}" ]; then
320                cp -a $fichero "${fichero}-${fecha}"
321        fi
322}
323
324# Restaura un fichero desde su copia de seguridad
325function restoreFile()
326{
327        if [ $# -ne 1 ]; then
328                errorAndLog "${FUNCNAME}(): invalid number of parameters"
329                exit 1
330        fi
331
332        local fichero=$1
333
334        echoAndLog "${FUNCNAME}(): restoring file $fichero"
335        if [ -f "${fichero}-LAST" ]; then
336                cp -a "$fichero-LAST" "$fichero"
337        fi
338}
339
340
341#####################################################################
342####### Funciones de acceso a base de datos
343#####################################################################
344
345# Actualizar la base datos
346function importSqlFile()
347{
348        if [ $# -ne 4 ]; then
349                errorAndLog "${FNCNAME}(): invalid number of parameters"
350                exit 1
351        fi
352
353        local dbuser="$1"
354        local dbpassword="$2"
355        local database="$3"
356        local sqlfile="$4"
357        local tmpfile=$(mktemp)
358        local mycnf=/tmp/.my.cnf.$$
359        local status
360
361        if [ ! -r $sqlfile ]; then
362                errorAndLog "${FUNCNAME}(): Unable to read $sqlfile!!"
363                return 1
364        fi
365
366        echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..."
367        chmod 600 $tmpfile
368        sed -e "s/SERVERIP/$SERVERIP/g" -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
369            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" $sqlfile > $tmpfile
370        # Componer fichero con credenciales de conexión. 
371        touch $mycnf
372        chmod 600 $mycnf
373        cat << EOT > $mycnf
374[client]
375user=$dbuser
376password=$dbpassword
377EOT
378        # Antes de actualizar, reasignar valores para campos no nulos con nulo por defecto.
379        mysql --defaults-extra-file=$MYCNF -D "$database" -e \
380                "$(mysql --defaults-extra-file=$MYCNF -Nse "
381SELECT CASE WHEN DATA_TYPE LIKE '%int' THEN
382                 CONCAT_WS(' ', 'ALTER TABLE', TABLE_NAME, 'ALTER', COLUMN_NAME, 'SET DEFAULT 0;')
383            WHEN DATA_TYPE LIKE '%char' THEN
384                 CONCAT_WS(' ', 'ALTER TABLE', TABLE_NAME, 'ALTER', COLUMN_NAME, 'SET DEFAULT \'\';')
385            WHEN DATA_TYPE = 'text' THEN
386                 CONCAT_WS(' ', 'ALTER TABLE', TABLE_NAME, 'MODIFY', COLUMN_NAME, 'TEXT NOT NULL;')
387            ELSE ''
388       END
389  FROM information_schema.COLUMNS
390 WHERE TABLE_SCHEMA='$database'
391   AND IS_NULLABLE='NO'
392   AND COLUMN_DEFAULT IS NULL
393   AND COLUMN_KEY='';")"
394        # Ejecutar actualización y borrar fichero de credenciales.
395        mysql --defaults-extra-file=$mycnf --default-character-set=utf8 -D "$database" < $tmpfile
396        status=$?
397        rm -f $mycnf $tmpfile
398        if [ $status -ne 0 ]; then
399                errorAndLog "${FUNCNAME}(): error importing $sqlfile in database $database"
400                return 1
401        fi
402        echoAndLog "${FUNCNAME}(): file imported to database $database"
403        return 0
404}
405
406# Comprobar configuración de MySQL y recomendar cambios necesarios.
407function checkMysqlConfig()
408{
409        echoAndLog "${FUNCNAME}(): checking MySQL configuration"
410
411        cp -a $WORKDIR/opengnsys/server/etc/mysqld-og.cnf $MYSQLCFGDIR 2>/dev/null
412        service=$MYSQLSERV; $STARTSERVICE
413
414        echoAndLog "${FUNCNAME}(): MySQL configuration has checked"
415        return 0
416}
417
418#####################################################################
419####### Funciones de instalación de paquetes
420#####################################################################
421
422# Instalar las deependencias necesarias para el actualizador.
423function installDependencies()
424{
425        local package
426
427        # Comprobar si hay que actualizar PHP 5 a PHP 7.
428        eval $UPDATEPKGLIST
429        if [ -f /etc/debian_version ]; then
430                # Basado en paquetes Deb.
431                PHP7VERSION="php7.2"
432                PHPFPMSERV="${PHP7VERSION}-fpm"
433                PHP5PKGS=( $(dpkg -l | awk '$2~/^php5/ {print $2}') )
434                if [ -n "$PHP5PKGS" ]; then
435                        $DELETEPKGS ${PHP5PKGS[@]}
436                        PHP5PKGS[0]="$PHP7VERSION"
437                        INSTALLDEPS=${PHP5PKGS[@]//php5*-/${PHP7VERSION}-}
438                fi
439        fi
440        if [ "$OSDISTRIB" == "centos" ]; then
441                PHP7VERSION=$(yum list -q php7\* 2>/dev/null | awk -F. '/^php/ {print $1; exit;}')
442                PHPFPMSERV="${PHP7VERSION}-${PHPFPMSERV}"
443                PHP5PKGS=( $(yum list installed | awk '$1~/^php/ && $2~/^5\./ {sub(/\..*$/, "", $1); print $1}') )
444                if [ -n "$PHP5PKGS" ]; then
445                        $DELETEPKGS ${PHP5PKGS[@]}
446                        PHP5PKGS[0]="$PHP7VERSION-php"
447                        INSTALLDEPS=${PHP5PKGS[@]//php-/${PHP7VERSION}-php}
448                fi
449        fi
450
451        if [ $# = 0 ]; then
452                echoAndLog "${FUNCNAME}(): no dependencies are needed"
453        else
454                while [ $# -gt 0 ]; do
455                        package="${1/php/$PHP7VERSION}"
456                        eval $CHECKPKG || INSTALLDEPS="$INSTALLDEPS $package"
457                        shift
458                done
459                if [ -n "$INSTALLDEPS" ]; then
460                        $INSTALLPKGS $INSTALLDEPS
461                        if [ $? -ne 0 ]; then
462                                errorAndLog "${FUNCNAME}(): cannot install some dependencies: $INSTALLDEPS"
463                                return 1
464                        fi
465                fi
466        fi
467}
468
469
470#####################################################################
471####### Funciones para descargar código
472#####################################################################
473
474function downloadCode()
475{
476        if [ $# -ne 1 ]; then
477                errorAndLog "${FUNCNAME}(): invalid number of parameters"
478                exit 1
479        fi
480
481        local url="$1"
482
483        echoAndLog "${FUNCNAME}(): downloading code..."
484
485        curl "$url" -o opengnsys.zip && \
486                unzip -qo opengnsys.zip && \
487                rm -fr opengnsys && \
488                mv "OpenGnsys-$BRANCH" opengnsys
489        if [ $? -ne 0 ]; then
490                errorAndLog "${FUNCNAME}(): error getting code from ${url}, verify your user and password"
491                return 1
492        fi
493        rm -f opengnsys.zip
494        echoAndLog "${FUNCNAME}(): code was downloaded"
495        return 0
496}
497
498
499############################################################
500###  Detectar red
501############################################################
502
503# Comprobar si existe conexión.
504function checkNetworkConnection()
505{
506        OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"opengnsys.es"}
507        if which curl &>/dev/null; then
508                curl --connect-timeout 10 -s "https://$OPENGNSYS_SERVER" -o /dev/null && \
509                        curl --connect-timeout 10 -s "http://$OPENGNSYS_SERVER" -o /dev/null
510        elif which wget &>/dev/null; then
511                wget --spider -q "https://$OPENGNSYS_SERVER" && \
512                        wget --spider -q "http://$OPENGNSYS_SERVER"
513        else
514                echoAndLog "${FUNCNAME}(): Cannot execute \"wget\" nor \"curl\"."
515                return 1
516        fi
517}
518
519# Comprobar si la versión es anterior a la actual.
520function checkVersion()
521{
522        local PRE
523
524        # Obtener versión actual y versión a actualizar.
525        [ -f $INSTALL_TARGET/doc/VERSION.txt ] && OLDVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt 2>/dev/null)
526        [ -f $INSTALL_TARGET/doc/VERSION.json ] && OLDVERSION=$(jq -r '.version' $INSTALL_TARGET/doc/VERSION.json 2>/dev/null)
527        if [ $REMOTE -eq 1 ]; then
528                NEWVERSION=$(curl -s $RAW_URL/doc/VERSION.json 2>/dev/null | jq -r '.version')
529        else
530                NEWVERSION=$(jq -r '.version' $PROGRAMDIR/../doc/VERSION.json 2>/dev/null)
531        fi
532        [[ "$NEWVERSION" =~ pre ]] && PRE=1
533
534        # Comparar versiones.
535        [[ "$NEWVERSION" < "${OLDVERSION/pre/}" ]] && return 1
536        [ "${NEWVERSION/pre/}" == "$OLDVERSION" -a "$PRE" == "1" ] && return 1
537
538        return 0
539}
540
541# Obtener los parámetros de red del servidor.
542function getNetworkSettings()
543{
544        # Variables globales definidas:
545        # - SERVERIP:   IP local de la interfaz por defecto.
546
547        local DEVICES
548        local dev
549
550        SERVERIP="$ServidorAdm"
551        DEVICES="$(ip -o link show up | awk '!/loopback/ {sub(/:.*/,"",$2); print $2}')"
552        for dev in $DEVICES; do
553                [ -z "$SERVERIP" ] && SERVERIP=$(ip -o addr show dev $dev | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4); exit;}')
554        done
555}
556
557
558#####################################################################
559####### Funciones específicas de la instalación de Opengnsys
560#####################################################################
561
562# Actualizar cliente OpenGnsys.
563function updateClientFiles()
564{
565        local ENGINECFG=$INSTALL_TARGET/client/etc/engine.cfg
566
567        # Actualizar ficheros del cliente.
568        backupFile $ENGINECFG
569        echoAndLog "${FUNCNAME}(): Updating OpenGnsys Client files"
570        rsync -irplt $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
571        if [ $? -ne 0 ]; then
572                errorAndLog "${FUNCNAME}(): error while updating client structure"
573                exit 1
574        fi
575
576        # Actualizar librerías del motor de clonación.
577        echoAndLog "${FUNCNAME}(): Updating OpenGnsys Cloning Engine files"
578        rsync -irplt $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
579        if [ $? -ne 0 ]; then
580                errorAndLog "${FUNCNAME}(): error while updating engine files"
581                exit 1
582        fi
583        # Actualizar fichero de configuración del motor de clonación.
584        if ! grep -q "^TZ" $ENGINECFG; then
585                TZ=$(timedatectl status | awk -F"[:()]" '/Time.*zone/ {print $2}')
586                cat << EOT >> $ENGINECFG
587# OpenGnsys Server timezone.
588TZ="${TZ// /}"
589EOT
590        fi
591        if ! diff -q ${ENGINECFG}{,-LAST} &>/dev/null; then
592                NEWFILES="$NEWFILES $ENGINECFG"
593        else
594                rm -f ${ENGINECFG}-LAST
595        fi
596        # Obtener URL para descargas adicionales.
597        DOWNLOADURL=$(oglivecli config download-url 2>/dev/null)
598        DOWNLOADURL=${DOWNLOADURL:-"https://$OPENGNSYS_SERVER/trac/downloads"}
599
600        echoAndLog "${FUNCNAME}(): client files successfully updated"
601}
602
603# Crear certificado para la firma de cargadores de arranque, si es necesario.
604function createCerts ()
605{
606        local SSLCFGDIR=$INSTALL_TARGET/client/etc/ssl
607        mkdir -p $SSLCFGDIR/{certs,private}
608        if [ ! -f $SSLCFGDIR/private/opengnsys.key ]; then
609                echoAndLog "${FUNCNAME}(): creating certificate files"
610                openssl req -new -x509 -newkey rsa:2048 -keyout $SSLCFGDIR/private/opengnsys.key -out $SSLCFGDIR/certs/opengnsys.crt -nodes -days 3650 -subj "/CN=OpenGnsys/"
611                openssl x509 -in $SSLCFGDIR/certs/opengnsys.crt -out $SSLCFGDIR/certs/opengnsys.cer -outform DER
612                echoAndLog "${FUNCNAME}(): certificate successfully created"
613        fi
614}
615
616# Configurar HTTPS y exportar usuario y grupo del servicio Apache.
617function apacheConfiguration ()
618{
619        local config template module socketfile
620
621        # Avtivar PHP-FPM.
622        echoAndLog "${FUNCNAME}(): configuring PHP-FPM"
623        service=$PHPFPMSERV
624        $ENABLESERVICE; $STARTSERVICE
625
626        # Activar módulos de Apache.
627        if [ -e $APACHECFGDIR/sites-available/opengnsys.conf ]; then
628                echoAndLog "${FUNCNAME}(): Configuring Apache modules"
629                a2ensite default-ssl
630                for module in $APACHEENABLEMODS; do a2enmod -q "$module"; done
631                for module in $APACHEDISABLEMODS; do a2dismod -q "${module//PHP7VERSION}"; done
632                a2ensite opengnsys
633        elif [ -e $APACHECFGDIR/conf.modules.d ]; then
634                echoAndLog "${FUNCNAME}(): Configuring Apache modules"
635                sed -i '/rewrite/s/^#//' $APACHECFGDIR/*.conf
636        fi
637        # Elegir plantilla según versión de Apache.
638        if [ -n "$(apachectl -v | grep "2\.[0-2]")" ]; then
639               template=$WORKDIR/opengnsys/server/etc/apache-prev2.4.conf.tmpl > $config
640        else
641               template=$WORKDIR/opengnsys/server/etc/apache.conf.tmpl
642        fi
643        sockfile=$(find /run/php -name "php*.sock" -type s -print 2>/dev/null | tail -1)
644        # Actualizar configuración de Apache a partir de fichero de plantilla.
645        for config in $APACHECFGDIR/{,sites-available/}opengnsys.conf; do
646                if [ -e $config ]; then
647                        if [ -n "$sockfile" ]; then
648                                sed -e "s,CONSOLEDIR,$INSTALL_TARGET/www,g; s,proxy:fcgi:.*,proxy:unix:${sockfile%% *}|fcgi://localhost\",g" $template > $config
649                        else
650                                sed -e "s,CONSOLEDIR,$INSTALL_TARGET/www,g" $template > $config
651                        fi
652                fi
653        done
654
655        # Reiniciar Apache.
656        service=$APACHESERV; $STARTSERVICE
657
658        # Variables de ejecución de Apache.
659        # - APACHE_RUN_USER
660        # - APACHE_RUN_GROUP
661        if [ -f $APACHECFGDIR/envvars ]; then
662                source $APACHECFGDIR/envvars
663        fi
664        APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
665        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
666}
667
668# Configurar servicio Rsync.
669function rsyncConfigure()
670{
671        local service
672
673        # Configurar acceso a Rsync.
674        if [ ! -f /etc/rsyncd.conf ]; then
675                echoAndLog "${FUNCNAME}(): Configuring Rsync service"
676                NEWFILES="$NEWFILES /etc/rsyncd.conf"
677                sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENTUSER/g" \
678                    $WORKDIR/opengnsys/repoman/etc/rsyncd.conf.tmpl > /etc/rsyncd.conf
679                # Habilitar Rsync.
680                if [ -f /etc/default/rsync ]; then
681                        perl -pi -e 's/RSYNC_ENABLE=.*/RSYNC_ENABLE=inetd/' /etc/default/rsync
682                fi
683                if [ -f $INETDCFGDIR/rsync ]; then
684                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/rsync
685                else
686                        cat << EOT > $INETDCFGDIR/rsync
687service rsync
688{
689        disable = no
690        socket_type = stream
691        wait = no
692        user = root
693        server = $(which rsync)
694        server_args = --daemon
695        log_on_failure += USERID
696        flags = IPv6
697}
698EOT
699                fi
700                # Activar e iniciar Rsync.
701                service="rsync"  $ENABLESERVICE
702                service="xinetd"
703                $ENABLESERVICE; $STARTSERVICE
704        fi
705}
706
707# Copiar ficheros del OpenGnsys Web Console.
708function updateWebFiles()
709{
710        local ERRCODE COMPATDIR f
711
712        echoAndLog "${FUNCNAME}(): Updating web files..."
713
714        # Copiar los ficheros nuevos conservando el archivo de configuración de acceso.
715        backupFile $INSTALL_TARGET/www/controlacceso.php
716        mv $INSTALL_TARGET/www $INSTALL_TARGET/WebConsole
717        rsync -irplt $WORKDIR/opengnsys/admin/WebConsole $INSTALL_TARGET
718        ERRCODE=$?
719        mv $INSTALL_TARGET/WebConsole $INSTALL_TARGET/www
720        rm -fr $INSTALL_TARGET/www/xajax
721        unzip -o $WORKDIR/opengnsys/admin/slim-2.6.1.zip -d $INSTALL_TARGET/www/rest
722        unzip -o $WORKDIR/opengnsys/admin/swagger-ui-2.2.5.zip -d $INSTALL_TARGET/www/rest
723        if [ $ERRCODE != 0 ]; then
724                errorAndLog "${FUNCNAME}(): Error updating web files."
725                exit 1
726        fi
727        restoreFile $INSTALL_TARGET/www/controlacceso.php
728
729        # Cambiar acceso a protocolo HTTPS.
730        if grep -q "http://" $INSTALL_TARGET/www/controlacceso.php 2>/dev/null; then
731                echoAndLog "${FUNCNAME}(): updating web access file"
732                perl -pi -e 's!http://!https://!g' $INSTALL_TARGET/www/controlacceso.php
733                NEWFILES="$NEWFILES $INSTALL_TARGET/www/controlacceso.php"
734        fi
735
736        # Compatibilidad con dispositivos móviles.
737        COMPATDIR="$INSTALL_TARGET/www/principal"
738        for f in acciones administracion aula aulas hardwares imagenes menus repositorios softwares; do
739                sed 's/clickcontextualnodo/clicksupnodo/g' $COMPATDIR/$f.php > $COMPATDIR/$f.device.php
740        done
741        cp -a $COMPATDIR/imagenes.device.php $COMPATDIR/imagenes.device4.php
742        # Acceso al manual de usuario
743        ln -fs ../doc/userManual $INSTALL_TARGET/www/userManual
744        # Fichero de log de la API REST.
745        touch $INSTALL_TARGET/log/{ogagent,rest,remotepc}.log
746
747        echoAndLog "${FUNCNAME}(): Web files successfully updated"
748}
749
750# Copiar ficheros en la zona de descargas de OpenGnsys Web Console.
751function updateDownloadableFiles()
752{
753        local VERSIONFILE OGVERSION FILENAME TARGETFILE
754
755        # Obtener versión a descargar.
756        VERSIONFILE="$INSTALL_TARGET/doc/VERSION.json"
757        OGVERSION="$(jq -r ".ogagent // \"$NEWVERSION\"" $VERSIONFILE 2>/dev/null || echo "$NEWVERSION")"
758        FILENAME="ogagentpkgs-$OGVERSION.tar.gz"
759        TARGETFILE=$WORKDIR/$FILENAME
760
761        # Descargar archivo comprimido, si es necesario.
762        if [ -s $PROGRAMDIR/$FILENAME ]; then
763                echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
764                mv $PROGRAMDIR/$FILENAME $TARGETFILE
765        else
766                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
767                curl $DOWNLOADURL/$FILENAME -o $TARGETFILE
768        fi
769        if [ ! -s $TARGETFILE ]; then
770                errorAndLog "${FUNCNAME}(): Cannot download $FILENAME"
771                return 1
772        fi
773
774        # Descomprimir fichero en zona de descargas.
775        tar xvzf $TARGETFILE -C $INSTALL_TARGET/www/descargas
776        if [ $? != 0 ]; then
777                errorAndLog "${FUNCNAME}(): Error uncompressing archive $FILENAME"
778                return 1
779        fi
780}
781
782# Copiar carpeta de Interface
783function updateInterfaceAdm()
784{
785        local errcode=0
786
787        # Crear carpeta y copiar Interface
788        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
789        mv $INSTALL_TARGET/client/interfaceAdm $INSTALL_TARGET/client/Interface
790        rsync -irplt $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client
791        errcoce=$?
792        mv $INSTALL_TARGET/client/Interface $INSTALL_TARGET/client/interfaceAdm
793        if [ $errcode -ne 0 ]; then
794                echoAndLog "${FUNCNAME}(): error while updating admin interface"
795                exit 1
796        fi
797        echoAndLog "${FUNCNAME}(): Admin interface successfully updated"
798}
799
800# Crear documentación Doxygen para la consola web.
801function makeDoxygenFiles()
802{
803        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
804        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
805                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
806        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
807                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files"
808                return 1
809        fi
810        rm -fr "$INSTALL_TARGET/www/api"
811        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
812        rm -fr $INSTALL_TARGET/www/{man,perlmod,rtf}
813        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully"
814}
815
816
817# Crea la estructura base de la instalación de opengnsys
818function createDirs()
819{
820        # Crear estructura de directorios.
821        echoAndLog "${FUNCNAME}(): creating directory paths in ${INSTALL_TARGET}"
822        local dir MKNETDIR
823
824        mkdir -p ${INSTALL_TARGET}/{bin,doc,etc,lib,sbin,www}
825        mkdir -p ${INSTALL_TARGET}/{client,images/groups}
826        mkdir -p ${INSTALL_TARGET}/log/clients
827        ln -fs ${INSTALL_TARGET}/log /var/log/opengnsys
828        # Detectar directorio de instalación de TFTP.
829        if [ ! -L ${INSTALL_TARGET}/tftpboot ]; then
830                for dir in /var/lib/tftpboot /srv/tftp; do
831                        [ -d $dir ] && ln -fs $dir ${INSTALL_TARGET}/tftpboot
832                done
833        fi
834        mkdir -p $INSTALL_TARGET/tftpboot/{menu.lst,grub}/examples
835        if [ $? -ne 0 ]; then
836                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
837                return 1
838        fi
839        ! [ -f $INSTALL_TARGET/tftpboot/menu.lst/templates/00unknown ] && mv $INSTALL_TARGET/tftpboot/menu.lst/templates/* $INSTALL_TARGET/tftpboot/menu.lst/examples
840        ! [ -f $INSTALL_TARGET/tftpboot/grub/templates/10 ] && mv $INSTALL_TARGET/tftpboot/grub/templates/* $INSTALL_TARGET/tftpboot/grub/examples
841
842        # Preparar arranque en red con Grub.
843        for f in grub-mknetdir grub2-mknetdir; do
844                if which $f &>/dev/null; then MKNETDIR=$f; fi
845        done
846        $MKNETDIR --net-directory=${INSTALL_TARGET}/tftpboot --subdir=grub
847
848        # Crear usuario ficticio.
849        if id -u $OPENGNSYS_CLIENTUSER &>/dev/null; then
850                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENTUSER\" is already created"
851        else
852                echoAndLog "${FUNCNAME}(): creating OpenGnsys user"
853                useradd $OPENGNSYS_CLIENTUSER 2>/dev/null
854                if [ $? -ne 0 ]; then
855                        errorAndLog "${FUNCNAME}(): error creating OpenGnsys user"
856                        return 1
857                fi
858        fi
859
860        # Mover el fichero de registro al directorio de logs.
861        echoAndLog "${FUNCNAME}(): moving update log file"
862        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
863        chmod 600 $LOG_FILE
864
865        echoAndLog "${FUNCNAME}(): directory paths created"
866        return 0
867}
868
869# Actualización incremental de la BD (versión actaul a actaul+1, hasta final-1 a final).
870function updateDatabase()
871{
872        local DBDIR="$WORKDIR/opengnsys/admin/Database"
873        local file FILES=""
874
875        echoAndLog "${FUNCNAME}(): looking for database updates"
876        pushd $DBDIR >/dev/null
877        # Bucle de actualización incremental desde versión actual a la final.
878        for file in $OPENGNSYS_DATABASE-*-*.sql; do
879                case "$file" in
880                        $OPENGNSYS_DATABASE-$OLDVERSION-$NEWVERSION.sql)
881                                # Actualización única de versión inicial y final.
882                                FILES="$FILES $file"
883                                break
884                                ;;
885                        $OPENGNSYS_DATABASE-*-postinst.sql)
886                                # Ignorar fichero específico de post-instalación.
887                                ;;
888                        $OPENGNSYS_DATABASE-$OLDVERSION-*.sql)
889                                # Actualización de versión n a n+1.
890                                FILES="$FILES $file"
891                                OLDVERSION="$(echo ${file%.*} | cut -f3 -d-)"
892                                ;;
893                        $OPENGNSYS_DATABASE-*-$NEWVERSION.sql)
894                                # Última actualización de versión final-1 a final.
895                                if [ -n "$FILES" ]; then
896                                        FILES="$FILES $file"
897                                        break
898                                fi
899                                ;;
900                esac
901        done
902        # Aplicar posible actualización propia para la versión final.
903        file=$OPENGNSYS_DATABASE-$NEWVERSION.sql
904        if [ -n "$FILES" -o "$OLDVERSION" = "$NEWVERSION" -a -r $file ]; then
905                FILES="$FILES $file"
906        fi
907
908        popd >/dev/null
909        if [ -n "$FILES" ]; then
910                for file in $FILES; do
911                        importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $DBDIR/$file
912                done
913                echoAndLog "${FUNCNAME}(): database is update"
914        else
915                echoAndLog "${FUNCNAME}(): database unchanged"
916        fi
917}
918
919# Copia ficheros de configuración y ejecutables genéricos del servidor.
920function updateServerFiles()
921{
922        # No copiar ficheros del antiguo cliente Initrd
923        local SOURCES=( repoman/bin \
924                        server/bin \
925                        server/lib \
926                        admin/Sources/Services/ogAdmRepoAux \
927                        server/tftpboot \
928                        /usr/lib/shim/shimx64.efi.signed \
929                        /usr/lib/grub/x86_64-efi-signed/grubnetx64.efi.signed \
930                        installer/opengnsys_uninstall.sh \
931                        installer/opengnsys_export.sh \
932                        installer/opengnsys_import.sh \
933                        doc )
934        local TARGETS=( bin \
935                        bin \
936                        lib \
937                        sbin/ogAdmRepoAux \
938                        tftpboot \
939                        tftpboot/shimx64.efi.signed \
940                        tftpboot/grubx64.efi \
941                        lib/opengnsys_uninstall.sh \
942                        lib/opengnsys_export.sh \
943                        lib/opengnsys_import.sh \
944                        doc )
945
946        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
947                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
948                exit 1
949        fi
950
951        echoAndLog "${FUNCNAME}(): updating files in server directories"
952        pushd $WORKDIR/opengnsys >/dev/null
953        local i
954        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
955                if [ -d "$INSTALL_TARGET/${TARGETS[i]}" ]; then
956                        rsync -irplt "${SOURCES[i]}" $(dirname $(readlink -e "$INSTALL_TARGET/${TARGETS[i]}"))
957                else
958                        rsync -irplt "${SOURCES[i]}" $(readlink -m "$INSTALL_TARGET/${TARGETS[i]}")
959                fi
960        done
961        popd >/dev/null
962        NEWFILES=""             # Ficheros de configuración que han cambiado de formato.
963        if grep -q 'pxelinux.0' /etc/dhcp*/dhcpd*.conf; then
964                echoAndLog "${FUNCNAME}(): updating DHCP files"
965                perl -pi -e 's/pxelinux.0/grldr/' /etc/dhcp*/dhcpd*.conf
966                service=$DHCPSERV; $STARTSERVICE
967                NEWFILES="/etc/dhcp*/dhcpd*.conf"
968        fi
969        if ! grep -q 'shimx64.efi.signed' /etc/dhcp*/dhcpd*.conf; then
970                echoAndLog "${FUNCNAME}(): updating DHCP files for UEFI computers"
971                UEFICFG="    # 0007 == x64 EFI boot\n"\
972"    if option arch = 00:07 {\n"\
973"        filename \"shimx64.efi.signed\";\n"\
974"    } else {\n"\
975"        filename \"grldr\";\n"\
976"    }"
977                sed -i -e 1i"option arch code 93 = unsigned integer 16;" -e s@"^.*grldr\"\;"@"$UEFICFG"@g /etc/dhcp*/dhcpd*.conf
978                service=$DHCPSERV; $STARTSERVICE
979                NEWFILES="/etc/dhcp*/dhcpd*.conf"
980        fi
981        if ! diff -q $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys 2>/dev/null; then
982                echoAndLog "${FUNCNAME}(): updating new init file"
983                backupFile /etc/init.d/opengnsys
984                service="opengnsys"
985                $STOPSERVICE
986                cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
987                systemctl daemon-reload
988                $STARTSERVICE
989                NEWFILES="$NEWFILES /etc/init.d/opengnsys"
990        fi
991        if ! diff -q \
992             $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.service \
993             /lib/systemd/system/opengnsys.service 2>/dev/null; then
994                echoAndLog "${FUNCNAME}(): updating new service file"
995                backupFile /lib/systemd/system/opengnsys.service
996                service="opengnsys"
997                $STOPSERVICE
998                cp -a \
999                   $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.service \
1000                   /lib/systemd/system/opengnsys.service
1001                systemctl daemon-reload
1002                $STARTSERVICE
1003                NEWFILES="$NEWFILES /lib/systemd/system/opengnsys.service"
1004        fi
1005        if ! diff -q $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default /etc/default/opengnsys >/dev/null; then
1006                echoAndLog "${FUNCNAME}(): updating new default file"
1007                backupFile /etc/default/opengnsys
1008                # Buscar si hay nuevos parámetros.
1009                local var valor
1010                while IFS="=" read -e var valor; do
1011                        [[ $var =~ ^# ]] || \
1012                                grep -q "^$var=" /etc/default/opengnsys || \
1013                                echo "$var=$valor" >> /etc/default/opengnsys
1014                done < $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default
1015                NEWFILES="$NEWFILES /etc/default/opengnsys"
1016        fi
1017
1018        echoAndLog "${FUNCNAME}(): updating cron files"
1019        [ ! -f /etc/cron.d/torrentcreator ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
1020        [ ! -f /etc/cron.d/torrenttracker ] && echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
1021        [ ! -f /etc/cron.d/imagedelete ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
1022        [ ! -f /etc/cron.d/ogagentqueue ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/ogagentqueue.cron ] && $INSTALL_TARGET/bin/ogagentqueue.cron" > /etc/cron.d/ogagentqueue
1023
1024        echoAndLog "${FUNCNAME}(): deleting deprecated cron file"
1025        [ -e /etc/cron.d/opengnsys ] && rm -f /etc/cron.d/opengnsys \
1026                                              $INSTALL_TARGET/bin/opengnsys.cron
1027
1028        # Se modifican los nombres de las plantilla PXE por compatibilidad con los equipos UEFI.
1029        if [ -f $INSTALL_TARGET/tftpboot/menu.lst/templates/01 ]; then
1030            BIOSPXEDIR="$INSTALL_TARGET/tftpboot/menu.lst/templates"
1031            mv $BIOSPXEDIR/01 $BIOSPXEDIR/10
1032            sed -i "s/\bMBR\b/1hd/" $BIOSPXEDIR/10
1033        fi
1034        echoAndLog "${FUNCNAME}(): server files successfully updated"
1035}
1036
1037####################################################################
1038### Funciones de compilación de código fuente de servicios
1039####################################################################
1040
1041# Mueve el fichero del nuevo servicio si es distinto al del directorio destino.
1042function moveNewService()
1043{
1044        local service
1045
1046        # Recibe 2 parámetros: fichero origen y directorio destino.
1047        [ $# == 2 ] || return 1
1048        [ -f  $1 -a -d $2 ] || return 1
1049
1050        # Comparar los ficheros.
1051        if ! diff -q $1 $2/$(basename $1) &>/dev/null; then
1052                # Parar los servicios si fuese necesario.
1053                service="opengnsys"
1054                [ -z "$NEWSERVICES" ] && $STOPSERVICE
1055                # Nuevo servicio.
1056                NEWSERVICES="$NEWSERVICES $(basename $1)"
1057                # Mover el nuevo fichero de servicio
1058                mv $1 $2
1059                $STARTSERVICE
1060        fi
1061}
1062
1063
1064# Compiling and updating OpenGnsys Server service
1065function ogServerCompilation()
1066{
1067        local ogserverUrl="https://codeload.github.com/opengnsys/ogServer/zip/$BRANCH"
1068        local error=0 serv
1069
1070        echoAndLog "${FUNCNAME}(): downloading ogServer code..."
1071
1072        if ! (curl "${ogserverUrl}" -o ogserver.zip && \
1073              unzip -qo "ogserver.zip")
1074        then
1075                errorAndLog "${FUNCNAME}(): "\
1076                            "error getting ogServer code from ${ogserverUrl}"
1077                return 1
1078        fi
1079        rm -f ogserver.zip
1080        echoAndLog "${FUNCNAME}(): ogServer code was downloaded"
1081
1082        echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Admin Server"
1083        pushd "$WORKDIR/ogServer-$BRANCH"
1084        autoreconf -fi && ./configure && make && moveNewService ogserver $INSTALL_TARGET/sbin
1085        if [ $? -ne 0 ]; then
1086                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Server"
1087                error=1
1088        fi
1089        popd
1090        # Renaming OpenGnsys Server configuration file, if needed
1091        [ -e $INSTALL_TARGET/etc/ogAdmServer.cfg ] && \
1092            rm -f $INSTALL_TARGET/etc/ogAdmServer.cfg
1093        [ -e $INSTALL_TARGET/etc/ogserver.cfg ] && \
1094            rm -f $INSTALL_TARGET/etc/ogserver.cfg
1095        if [ ! -e $INSTALL_TARGET/etc/ogserver.json ]; then
1096                echo "{
1097                        \"rest\" : {
1098                                \"ip\" : \"$ServidorAdm\",
1099                                \"port\" : \"8888\",
1100                                \"api_token\": \"$APITOKEN\"
1101                        },
1102                        \"database\" : {
1103                                \"ip\": \"$datasource\",
1104                                \"port\": \"3306\",
1105                                \"name\" : \"$CATALOG\",
1106                                \"user\" : \"$USUARIO\",
1107                                \"pass\" : \"$PASSWORD\"
1108                        },
1109                        \"wol\" : {
1110                                \"interface\" : \"$INTERFACE\"
1111                        }
1112                }" | jq '.' > "$INSTALL_TARGET"/etc/ogserver.json
1113        fi
1114        # Remove old OpenGnsys services
1115        for serv in ogAdmAgent ogAdmRepo ogAdmServer; do
1116                pgrep $serv > /dev/null && pkill -9 $serv && \
1117                    echoAndLog "${FUNCNAME}(): removing deprecated $serv service"
1118                rm -f $INSTALL_TARGET/sbin/$serv
1119                if [ $serv != ogAdmRepo ]; then
1120                        rm -f $INSTALL_TARGET/etc/$serv.cfg
1121                fi
1122        done
1123        # Generating an ogServer API token, if it does not exist
1124        [ -z "$APITOKEN" ] && \
1125            $INSTALL_TARGET/bin/settoken -f
1126        # Updating service file, if needed
1127        if ! diff -q \
1128             "$WORKDIR"/ogServer-"$BRANCH"/cfg/ogserver.service \
1129             /lib/systemd/system/ogserver.service 2>/dev/null; then
1130                service="opengnsys"
1131                $STOPSERVICE
1132                echoAndLog "${FUNCNAME}(): updating new service file"
1133                backupFile /lib/systemd/system/ogserver.service
1134                service="ogserver"
1135                $STOPSERVICE
1136                cp -a \
1137                   "$WORKDIR"/ogServer-"$BRANCH"/cfg/ogserver.service \
1138                   /lib/systemd/system/ogserver.service
1139                systemctl daemon-reload
1140                $STARTSERVICE
1141                service="opengnsys"
1142                $STARTSERVICE
1143                NEWFILES="$NEWFILES /lib/systemd/system/ogserver.service"
1144        fi
1145
1146        return $error
1147}
1148
1149
1150####################################################################
1151### Funciones instalacion cliente OpenGnsys
1152####################################################################
1153
1154# Actualizar cliente OpenGnsys
1155function updateClient()
1156{
1157        #local FILENAME=ogLive-precise-3.2.0-23-generic-r5159.iso       # 1.1.0-rc6 (32-bit)
1158        local FILENAME=ogLive-bionic-5.0.0-27-generic-amd64-r20190830.7208cc9.iso       # 1.1.1-rc5
1159        local SOURCEFILE=$DOWNLOADURL/$FILENAME
1160        local TARGETFILE=$(oglivecli config download-dir)/$FILENAME
1161        local SOURCELENGTH
1162        local TARGETLENGTH
1163        local OGINITRD
1164        local SAMBAPASS
1165
1166        # Comprobar si debe convertirse el antiguo cliente al nuevo formato ogLive.
1167        if oglivecli check | grep -q "oglivecli convert"; then
1168                echoAndLog "${FUNCNAME}(): Converting OpenGnsys Client to default ogLive"
1169                oglivecli convert
1170        fi
1171        # Comprobar si debe actualizarse el cliente.
1172        SOURCELENGTH=$(curl -sI $SOURCEFILE 2>&1 | awk '/Content-Length:/ {gsub("\r", ""); print $2}')
1173        TARGETLENGTH=$(stat -c "%s" $TARGETFILE 2>/dev/null)
1174        [ -z $TARGETLENGTH ] && TARGETLENGTH=0
1175        if [ "$SOURCELENGTH" != "$TARGETLENGTH" ]; then
1176                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
1177                oglivecli download $FILENAME
1178                if [ ! -s $TARGETFILE ]; then
1179                        errorAndLog "${FUNCNAME}(): Error downloading $FILENAME"
1180                        return 1
1181                fi
1182                # Actaulizar la imagen ISO del ogclient.
1183                echoAndLog "${FUNCNAME}(): Updatting ogLive client"
1184                oglivecli install $FILENAME
1185               
1186                INSTALLEDOGLIVE=${FILENAME%.*}
1187
1188                echoAndLog "${FUNCNAME}(): ogLive successfully updated"
1189        else
1190                # Si no existe, crear el fichero de claves de Rsync.
1191                if [ ! -f /etc/rsyncd.secrets ]; then
1192                        echoAndLog "${FUNCNAME}(): Restoring ogLive access key"
1193                        OGINITRD=$(oglivecli config install-dir)/$(jq -r ".oglive[.default].directory")/oginitrd.img
1194                        SAMBAPASS=$(gzip -dc $OGINITRD | \
1195                                    cpio -i --to-stdout scripts/ogfunctions 2>&1 | \
1196                                    grep "^[    ].*OPTIONS=" | \
1197                                    sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
1198                        echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | setsmbpass
1199                else
1200                        echoAndLog "${FUNCNAME}(): ogLive is already updated"
1201                fi
1202                # Versión del ogLive instalado.
1203                echo "${FILENAME%.*}" > $INSTALL_TARGET/doc/veroglive.txt
1204        fi
1205}
1206
1207# Update ogClient
1208function updateOgClient()
1209{
1210        local ogclientUrl="https://codeload.github.com/opengnsys/ogClient/zip/$BRANCH"
1211
1212        echoAndLog "${FUNCNAME}(): downloading ogClient code..."
1213
1214        if ! (curl "${ogclientUrl}" -o ogclient.zip && \
1215             unzip -qo ogclient.zip)
1216        then
1217                errorAndLog "${FUNCNAME}(): "\
1218                            "error getting ogClient code from ${ogclientUrl}"
1219                return 1
1220        fi
1221        if [ -e $INSTALL_TARGET/client/ogClient/cfg/ogclient.json ]; then
1222             rm -f ogClient-"$BRANCH"/cfg/ogclient.json
1223        fi
1224        rsync -irplt "ogClient-$BRANCH/" $INSTALL_TARGET/client/ogClient
1225        rm -f ogclient.zip
1226        echoAndLog "${FUNCNAME}(): ogClient code was downloaded and updated"
1227
1228        return 0
1229}
1230
1231# Comprobar permisos y ficheros.
1232function checkFiles()
1233{
1234        local LOGROTATEDIR=/etc/logrotate.d
1235
1236        # Comprobar permisos adecuados.
1237        if [ -x $INSTALL_TARGET/bin/checkperms ]; then
1238                echoAndLog "${FUNCNAME}(): Checking permissions"
1239                OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENTUSER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" $INSTALL_TARGET/bin/checkperms
1240        fi
1241        # Eliminamos el fichero de estado del tracker porque es incompatible entre los distintos paquetes
1242        if [ -f /tmp/dstate ]; then
1243                echoAndLog "${FUNCNAME}(): Deleting unused files"
1244                rm -f /tmp/dstate
1245        fi
1246        # Crear nuevos ficheros de logrotate y borrar el fichero antiguo.
1247        if [ -d $LOGROTATEDIR ]; then
1248                rm -f $LOGROTATEDIR/opengnsys
1249                if [ ! -f $LOGROTATEDIR/opengnsysServer ]; then
1250                        echoAndLog "${FUNCNAME}(): Creating logrotate configuration file for server"
1251                        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1252                                $WORKDIR/opengnsys/server/etc/logrotate.tmpl > $LOGROTATEDIR/opengnsysServer
1253                fi
1254                if [ ! -f $LOGROTATEDIR/opengnsysRepo ]; then
1255                        echoAndLog "${FUNCNAME}(): Creating logrotate configuration file for repository"
1256                        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1257                                $WORKDIR/opengnsys/server/etc/logrotate.tmpl > $LOGROTATEDIR/opengnsysRepo
1258                fi
1259        fi
1260}
1261
1262# Resumen de actualización.
1263function updateSummary()
1264{
1265        # Actualizar fichero de versión y revisión.
1266        local VERSIONFILE REVISION
1267        VERSIONFILE="$INSTALL_TARGET/doc/VERSION.json"
1268        # Obtener revisión.
1269        if [ $REMOTE -eq 1 ]; then
1270                # Revisión: rAñoMesDía.Gitcommit (8 caracteres de fecha y 7 primeros de commit).
1271                if [ "$BRANCH" = "master" ]; then
1272                        REVISION=$(curl -s "$API_URL" | jq '"r" + (.commit.commit.committer.date | split("-") | join("")[:8]) + "." + (.commit.sha[:7])')
1273                else
1274                        REVISION=$(curl -s "$API_URL" | jq '"r" + (.commit.committer.date | split("-") | join("")[:8]) + "." + (.sha[:7])')
1275                fi
1276        else
1277                # Parámetro "release" del fichero JSON.
1278                REVISION=$(jq -r '.release' $PROGRAMDIR/../doc/VERSION.json 2>/dev/null)
1279        fi
1280        [ -f $VERSIONFILE ] || echo '{ "project": "OpenGnsys" }' > $VERSIONFILE
1281        jq ".release=$REVISION" $VERSIONFILE | sponge $VERSIONFILE
1282        VERSION="$(jq -r '[.project, .version, .codename, .release] | join(" ")' $VERSIONFILE 2>/dev/null)"
1283        # Borrar antiguo fichero de versión.
1284        rm -f "${VERSIONFILE/json/txt}"
1285
1286        echo
1287        echoAndLog "OpenGnsys Update Summary"
1288        echo       "========================"
1289        echoAndLog "Project version:                  $VERSION"
1290        echoAndLog "Update log file:                  $LOG_FILE"
1291        [ "$NEWFILES" ] && echoAndLog "Check new config files:           $(echo $NEWFILES)"
1292        [ "$NEWSERVICES" ] && echoAndLog "New compiled services:            $(echo $NEWSERVICES)"
1293        echoAndLog "Warnings:"
1294        echoAndLog " - You must to clear web browser cache before loading OpenGnsys page"
1295        echoAndLog " - Run \"settoken\" script to update authentication tokens"
1296        [ "$INSTALLEDOGLIVE" ] && echoAndLog " - Installed new ogLive Client: $INSTALLEDOGLIVE"
1297        echoAndLog " - If you want to use BURG as boot manager, run following command as root:"
1298        echoAndLog "      curl $DOWNLOADURL/burg.tgz -o $INSTALL_TARGET/client/lib/burg.tgz"
1299
1300        echo
1301}
1302
1303
1304
1305#####################################################################
1306####### Proceso de actualización de OpenGnsys
1307#####################################################################
1308
1309
1310# Comprobar si hay conexión y detectar parámetros de red por defecto.
1311checkNetworkConnection
1312if [ $? -ne 0 ]; then
1313        errorAndLog "Error connecting to server. Causes:"
1314        errorAndLog " - Network is unreachable, check device parameters"
1315        errorAndLog " - You are inside a private network, configure the proxy service"
1316        errorAndLog " - Server is temporally down, try again later"
1317        exit 1
1318fi
1319getNetworkSettings
1320
1321# Elegir versión y comprobar si se intanta actualizar a una versión anterior.
1322chooseVersion
1323checkVersion
1324if [ $? -ne 0 ]; then
1325        errorAndLog "Cannot downgrade to an older version ($OLDVERSION to $NEWVERSION)"
1326        errorAndLog "You must to uninstall OpenGnsys and install desired release"
1327        exit 1
1328fi
1329
1330echoAndLog "OpenGnsys update begins at $(date)"
1331pushd $WORKDIR
1332
1333# Comprobar auto-actualización del programa.
1334if [ "$PROGRAMDIR" != "$INSTALL_TARGET/bin" ]; then
1335        checkAutoUpdate
1336        if [ $? -ne 0 ]; then
1337                echoAndLog "OpenGnsys updater has been overwritten"
1338                echoAndLog "Please, run this script again"
1339                exit
1340        fi
1341fi
1342
1343# Detectar datos de auto-configuración del instalador.
1344autoConfigure
1345
1346# Instalar dependencias.
1347installDependencies ${DEPENDENCIES[*]}
1348if [ $? -ne 0 ]; then
1349        errorAndLog "Error: you must to install all needed dependencies"
1350        exit 1
1351fi
1352
1353# Arbol de directorios de OpenGnsys.
1354createDirs ${INSTALL_TARGET}
1355if [ $? -ne 0 ]; then
1356        errorAndLog "Error while creating directory paths"
1357        exit 1
1358fi
1359
1360# Si es necesario, descarga el repositorio de código en directorio temporal
1361if [ $REMOTE -eq 1 ]; then
1362        downloadCode $CODE_URL
1363        if [ $? -ne 0 ]; then
1364                errorAndLog "Error while getting code from repository"
1365                exit 1
1366        fi
1367else
1368        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
1369fi
1370
1371# Comprobar configuración de MySQL.
1372checkMysqlConfig $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD
1373
1374# Actualizar la BD.
1375updateDatabase
1376
1377# Actualizar ficheros complementarios del servidor
1378updateServerFiles
1379if [ $? -ne 0 ]; then
1380        errorAndLog "Error updating OpenGnsys Server files"
1381        exit 1
1382fi
1383
1384# Configurar Rsync.
1385rsyncConfigure
1386
1387# Actualizar ficheros del cliente.
1388updateClientFiles
1389createCerts
1390updateInterfaceAdm
1391
1392# Actualizar páqinas web.
1393apacheConfiguration
1394updateWebFiles
1395if [ $? -ne 0 ]; then
1396        errorAndLog "Error updating OpenGnsys Web Admin files"
1397        exit 1
1398fi
1399# Actaulizar ficheros descargables.
1400updateDownloadableFiles
1401# Generar páginas Doxygen para instalar en el web
1402makeDoxygenFiles
1403
1404# Recompilar y actualizar los servicios del sistema
1405if ogServerCompilation; then
1406        # Restart services, if necessary.
1407        if [ "$NEWSERVICES" ]; then
1408                echoAndLog "Restarting OpenGnsys services"
1409                service="opengnsys" $STARTSERVICE
1410        fi
1411else
1412        errorAndLog "Error compiling OpenGnsys services"
1413        exit 1
1414fi
1415
1416# Actaulizar ficheros auxiliares del cliente
1417updateClient
1418if [ $? -ne 0 ]; then
1419        errorAndLog "Error updating client files"
1420        exit 1
1421fi
1422
1423# Update ogClient
1424if ! updateOgClient; then
1425        errorAndLog "Error updating ogClient files"
1426        exit 1
1427fi
1428
1429# Comprobar permisos y ficheros.
1430checkFiles
1431
1432# Mostrar resumen de actualización.
1433updateSummary
1434
1435rm -rf $WORKDIR
1436echoAndLog "OpenGnsys update finished at $(date)"
1437
1438popd
1439
Note: See TracBrowser for help on using the repository browser.