source: installer/opengnsys_update.sh @ 2a0c332

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

#840: Checking permissions and directories after Git downloads.

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