source: installer/opengnsys_update.sh @ 2831647

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

#946: Update script keeps stable version when downloading OGAgent packages.

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