source: installer/opengnsys_update.sh @ 518d4d8

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 518d4d8 was 59d6670, checked in by Ramón M. Gómez <ramongomez@…>, 6 years ago

#846: Remove appropiate logrotate files when uninstalling or updating.

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