source: installer/opengnsys_update.sh @ 7d8d8af

918-git-images-111dconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacion
Last change on this file since 7d8d8af was 1479f77, checked in by Ramón M. Gómez <ramongomez@…>, 5 years ago

#941: Add new installation dependencies to compile services.

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