source: installer/opengnsys_update.sh @ a37e5fc4

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 a37e5fc4 was a37e5fc4, checked in by ramon <ramongomez@…>, 7 years ago

#804: Instalar y actualizar a PHP 7.

git-svn-id: https://opengnsys.es/svn/branches/version1.1@5638 a21b9725-9963-47de-94b9-378ad31fedc9

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