source: installer/opengnsys_update.sh

lgromero-new-oglive
Last change on this file was d3ec014, checked in by Irina Gómez <irinagomez@…>, 11 months ago

Resolves vulnerabilities CVE-2024-3704, CVE-2024-3705, CVE-2024-3706 y CVE-2024-3707.

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