source: installer/opengnsys_update.sh @ 9815cac

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 9815cac was 9815cac, checked in by Ramón M. Gómez <ramongomez@…>, 7 years ago

#843: Scripts in inCaller directory use new version file.

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