source: installer/opengnsys_update.sh @ c583144

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

#986 Rename to ogserver

Step forward to rename all ogAdmServer references to ogServer

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