source: installer/opengnsys_update.sh

qndtest
Last change on this file was 73c5e1c, checked in by Irina Gómez <irinagomez@…>, 23 months ago

#1066 Changes devel branch name.

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