source: installer/opengnsys_update.sh @ a0dd47a

Last change on this file since a0dd47a was 0e3e167, checked in by Ramón M. Gómez <ramongomez@…>, 5 years ago

#997: Support for Initrd compressed in several formats.

Adding compatibility with Ubuntu 20.04 Initrd, which is compressed in LZ4 format.

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