source: installer/opengnsys_update.sh @ 9215580

918-git-images-111dconfigfileconfigure-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-instalacionwebconsole3
Last change on this file since 9215580 was 9215580, checked in by Ramón M. Gómez <ramongomez@…>, 7 years ago

#784: Using PHP-FPM instead of Mod-PHP to improve Apache performance.

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