source: installer/opengnsys_update.sh @ 0433dbe

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

#886: Backward-compatible with JQ version 1.4

  • Property mode set to 100755
File size: 40.4 KB
Line 
1#!/bin/bash
2#/**
3#@file    opengnsys_update.sh
4#@brief   Script actualización de OpenGnsys
5#@version 0.9 - basado en opengnsys_installer.sh
6#@author  Ramón Gómez - ETSII Univ. Sevilla
7#@date    2010/01/27
8#@version 1.0 - adaptación a OpenGnSys 1.0
9#@author  Ramón Gómez - ETSII Univ. Sevilla
10#@date    2011/03/02
11#@version 1.0.1 - control de auto actualización del script
12#@author  Ramón Gómez - ETSII Univ. Sevilla
13#@date    2011/05/17
14#@version 1.0.2a - obtiene valor de dirección IP por defecto
15#@author  Ramón Gómez - ETSII Univ. Sevilla
16#@date    2012/01/18
17#@version 1.0.3 - Compatibilidad con Debian y auto configuración de acceso a BD.
18#@author  Ramón Gómez - ETSII Univ. Sevilla
19#@date    2012/03/12
20#@version 1.0.4 - Detector de distribución y compatibilidad con CentOS.
21#@author  Ramón Gómez - ETSII Univ. Sevilla
22#@date    2012/05/04
23#@version 1.0.5 - Actualizar BD en la misma versión, compatibilidad con Fedora (systemd) y configuración de Rsync.
24#@author  Ramón Gómez - ETSII Univ. Sevilla
25#@date    2014/04/03
26#@version 1.0.6 - Redefinir URLs de ficheros de configuración usando HTTPS.
27#@author  Ramón Gómez - ETSII Univ. Sevilla
28#@date    2015/03/12
29#@version 1.1.0 - Instalación de API REST y configuración de zona horaria.
30#@author  Ramón Gómez - ETSII Univ. Sevilla
31#@date    2015/11/09
32#*/
33
34
35####  AVISO: NO EDITAR variables de configuración.
36####  WARNING: DO NOT EDIT configuration variables.
37INSTALL_TARGET=/opt/opengnsys           # Directorio de instalación
38PATH=$PATH:$INSTALL_TARGET/bin
39OPENGNSYS_CLIENTUSER="opengnsys"        # Usuario Samba
40
41
42# Sólo ejecutable por usuario root
43if [ "$(whoami)" != 'root' ]; then
44        echo "ERROR: this program must run under root privileges!!"
45        exit 1
46fi
47# Error si OpenGnsys no está instalado (no existe el directorio del proyecto)
48if [ ! -d $INSTALL_TARGET ]; then
49        echo "ERROR: OpenGnsys is not installed, cannot update!!"
50        exit 1
51fi
52# Cargar configuración de acceso a la base de datos.
53if [ -r $INSTALL_TARGET/etc/ogAdmServer.cfg ]; then
54        source $INSTALL_TARGET/etc/ogAdmServer.cfg
55elif [ -r $INSTALL_TARGET/etc/ogAdmAgent.cfg ]; then
56        source $INSTALL_TARGET/etc/ogAdmAgent.cfg
57fi
58OPENGNSYS_DATABASE=${OPENGNSYS_DATABASE:-"$CATALOG"}            # Base de datos
59OPENGNSYS_DBUSER=${OPENGNSYS_DBUSER:-"$USUARIO"}                # Usuario de acceso
60OPENGNSYS_DBPASSWORD=${OPENGNSYS_DBPASSWORD:-"$PASSWORD"}       # Clave del usuario
61if [ -z "$OPENGNSYS_DATABASE" -o -z "$OPENGNSYS_DBUSER" -o -z "$OPENGNSYS_DBPASSWORD" ]; then
62        echo "ERROR: set OPENGNSYS_DATABASE, OPENGNSYS_DBUSER and OPENGNSYS_DBPASSWORD"
63        echo "       variables, and run this script again."
64        exit 1
65fi
66
67# Comprobar si se ha descargado el paquete comprimido (REMOTE=0) o sólo el instalador (REMOTE=1).
68PROGRAMDIR=$(readlink -e $(dirname "$0"))
69PROGRAMNAME=$(basename "$0")
70OPENGNSYS_SERVER="opengnsys.es"
71if [ -d "$PROGRAMDIR/../installer" ]; then
72        REMOTE=0
73else
74        REMOTE=1
75fi
76BRANCH="devel"
77CODE_URL="https://codeload.github.com/opengnsys/OpenGnsys/zip/$BRANCH"
78API_URL="https://api.github.com/repos/opengnsys/OpenGnsys/branches/$BRANCH"
79RAW_URL="https://raw.githubusercontent.com/opengnsys/OpenGnsys/$BRANCH"
80
81WORKDIR=/tmp/opengnsys_update
82mkdir -p $WORKDIR
83
84# Registro de incidencias.
85OGLOGFILE=$INSTALL_TARGET/log/${PROGRAMNAME%.sh}.log
86LOG_FILE=/tmp/$(basename $OGLOGFILE)
87
88
89
90#####################################################################
91####### Algunas funciones útiles de propósito general:
92#####################################################################
93
94# Generar variables de configuración del actualizador
95# Variables globales:
96# - OSDISTRIB - distribución Linux
97# - DEPENDENCIES - array de dependencias que deben estar instaladas
98# - UPDATEPKGLIST, INSTALLPKGS, CHECKPKG - comandos para gestión de paquetes
99# - APACHECFGDIR, APACHESERV, 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 ! diff -q $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default /etc/default/opengnsys >/dev/null; then
891                echoAndLog "${FUNCNAME}(): updating new default file"
892                backupFile /etc/default/opengnsys
893                # Buscar si hay nuevos parámetros.
894                local var valor
895                while IFS="=" read -e var valor; do
896                        [[ $var =~ ^# ]] || \
897                                grep -q "^$var=" /etc/default/opengnsys || \
898                                echo "$var=$valor" >> /etc/default/opengnsys
899                done < $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default
900                NEWFILES="$NEWFILES /etc/default/opengnsys"
901        fi
902        if egrep -q "(UrlMsg=.*msgbrowser.php)|(UrlMenu=http://)" $INSTALL_TARGET/client/etc/ogAdmClient.cfg 2>/dev/null; then
903                echoAndLog "${FUNCNAME}(): updating new client config file"
904                backupFile $INSTALL_TARGET/client/etc/ogAdmClient.cfg
905                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
906                NEWFILES="$NEWFILES $INSTALL_TARGET/client/etc/ogAdmClient.cfg"
907        fi
908
909        echoAndLog "${FUNCNAME}(): updating cron files"
910        [ ! -f /etc/cron.d/opengnsys ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
911        [ ! -f /etc/cron.d/torrentcreator ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
912        [ ! -f /etc/cron.d/torrenttracker ] && echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
913        [ ! -f /etc/cron.d/imagedelete ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
914        [ ! -f /etc/cron.d/ogagentqueue ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/ogagentqueue.cron ] && $INSTALL_TARGET/bin/ogagentqueue.cron" > /etc/cron.d/ogagentqueue
915        echoAndLog "${FUNCNAME}(): server files successfully updated"
916}
917
918####################################################################
919### Funciones de compilación de código fuente de servicios
920####################################################################
921
922# Mueve el fichero del nuevo servicio si es distinto al del directorio destino.
923function moveNewService()
924{
925        local service
926
927        # Recibe 2 parámetros: fichero origen y directorio destino.
928        [ $# == 2 ] || return 1
929        [ -f  $1 -a -d $2 ] || return 1
930
931        # Comparar los ficheros.
932        if ! diff -q $1 $2/$(basename $1) &>/dev/null; then
933                # Parar los servicios si fuese necesario.
934                [ -z "$NEWSERVICES" ] && service="opengnsys" $STOPSERVICE
935                # Nuevo servicio.
936                NEWSERVICES="$NEWSERVICES $(basename $1)"
937                # Mover el nuevo fichero de servicio
938                mv $1 $2
939        fi
940}
941
942
943# Recompilar y actualiza los serivicios y clientes.
944function compileServices()
945{
946        local hayErrores=0
947
948        # Compilar OpenGnsys Server
949        echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Admin Server"
950        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
951        make && moveNewService ogAdmServer $INSTALL_TARGET/sbin
952        if [ $? -ne 0 ]; then
953                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Server"
954                hayErrores=1
955        fi
956        popd
957        # Parar antiguo servicio de repositorio y añadir clave de acceso REST en su fichero de configuración.
958        pgrep ogAdmRepo > /dev/null && service="ogAdmRepo" $STOPSERVICE
959        grep -q '^ApiToken=' $INSTALL_TARGET/etc/ogAdmRepo.cfg && \
960                sed -i "s/^ApiToken=.*$/ApiToken=$REPOKEY/" $INSTALL_TARGET/etc/ogAdmRepo.cfg || \
961                sed -i "$ a\ApiToken=$REPOKEY/" $INSTALL_TARGET/etc/ogAdmRepo.cfg
962        # Compilar OpenGnsys Agent
963        echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Server Agent"
964        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
965        make && moveNewService ogAdmAgent $INSTALL_TARGET/sbin
966        if [ $? -ne 0 ]; then
967                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Server Agent"
968                hayErrores=1
969        fi
970        popd
971
972        # Compilar OpenGnsys Client
973        echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Client"
974        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
975        make && mv ogAdmClient $INSTALL_TARGET/client/bin
976        if [ $? -ne 0 ]; then
977                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Client"
978                hayErrores=1
979        fi
980        popd
981
982        return $hayErrores
983}
984
985
986####################################################################
987### Funciones instalacion cliente OpenGnsys
988####################################################################
989
990# Actualizar cliente OpenGnsys
991function updateClient()
992{
993        #local FILENAME=ogLive-precise-3.2.0-23-generic-r5159.iso       # 1.1.0-rc6 (old)
994        local FILENAME=ogLive-xenial-4.13.0-17-generic-amd64-r5520.iso  # 1.1.0-rc6
995        local SOURCEFILE=$DOWNLOADURL/$FILENAME
996        local TARGETFILE=$(oglivecli config download-dir)/$FILENAME
997        local SOURCELENGTH
998        local TARGETLENGTH
999        local OGINITRD
1000        local SAMBAPASS
1001
1002        # Comprobar si debe convertirse el antiguo cliente al nuevo formato ogLive.
1003        if oglivecli check | grep -q "oglivecli convert"; then
1004                echoAndLog "${FUNCNAME}(): Converting OpenGnsys Client to default ogLive"
1005                oglivecli convert
1006        fi
1007        # Comprobar si debe actualizarse el cliente.
1008        SOURCELENGTH=$(curl -sI $SOURCEFILE 2>&1 | awk '/Content-Length:/ {gsub("\r", ""); print $2}')
1009        TARGETLENGTH=$(stat -c "%s" $TARGETFILE 2>/dev/null)
1010        [ -z $TARGETLENGTH ] && TARGETLENGTH=0
1011        if [ "$SOURCELENGTH" != "$TARGETLENGTH" ]; then
1012                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
1013                oglivecli download $FILENAME
1014                if [ ! -s $TARGETFILE ]; then
1015                        errorAndLog "${FUNCNAME}(): Error downloading $FILENAME"
1016                        return 1
1017                fi
1018                # Actaulizar la imagen ISO del ogclient.
1019                echoAndLog "${FUNCNAME}(): Updatting ogLive client"
1020                oglivecli install $FILENAME
1021               
1022                CLIENTUPDATED=${FILENAME%.*}
1023
1024                echoAndLog "${FUNCNAME}(): ogLive successfully updated"
1025        else
1026                # Si no existe, crear el fichero de claves de Rsync.
1027                if [ ! -f /etc/rsyncd.secrets ]; then
1028                        echoAndLog "${FUNCNAME}(): Restoring ogLive access key"
1029                        OGINITRD=$(oglivecli config install-dir)/$(jq -r ".oglive[.default].directory")/oginitrd.img
1030                        SAMBAPASS=$(gzip -dc $OGINITRD | \
1031                                    cpio -i --to-stdout scripts/ogfunctions 2>&1 | \
1032                                    grep "^[    ].*OPTIONS=" | \
1033                                    sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
1034                        echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | setsmbpass
1035                else
1036                        echoAndLog "${FUNCNAME}(): ogLive is already updated"
1037                fi
1038                # Versión del ogLive instalado.
1039                echo "${FILENAME%.*}" > $INSTALL_TARGET/doc/veroglive.txt
1040        fi
1041}
1042
1043# Comprobar permisos y ficheros.
1044function checkFiles()
1045{
1046        local LOGROTATEDIR=/etc/logrotate.d
1047
1048        # Comprobar permisos adecuados.
1049        if [ -x $INSTALL_TARGET/bin/checkperms ]; then
1050                echoAndLog "${FUNCNAME}(): Checking permissions"
1051                OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENTUSER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" $INSTALL_TARGET/bin/checkperms
1052        fi
1053        # Eliminamos el fichero de estado del tracker porque es incompatible entre los distintos paquetes
1054        if [ -f /tmp/dstate ]; then
1055                echoAndLog "${FUNCNAME}(): Deleting unused files"
1056                rm -f /tmp/dstate
1057        fi
1058        # Crear nuevos ficheros de logrotate y borrar el fichero antiguo.
1059        if [ -d $LOGROTATEDIR ]; then
1060                rm -f $LOGROTATEDIR/opengnsys
1061                if [ ! -f $LOGROTATEDIR/opengnsysServer ]; then
1062                        echoAndLog "${FUNCNAME}(): Creating logrotate configuration file for server"
1063                        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1064                                $WORKDIR/opengnsys/server/etc/logrotate.tmpl > $LOGROTATEDIR/opengnsysServer
1065                fi
1066                if [ ! -f $LOGROTATEDIR/opengnsysRepo ]; then
1067                        echoAndLog "${FUNCNAME}(): Creating logrotate configuration file for repository"
1068                        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1069                                $WORKDIR/opengnsys/server/etc/logrotate.tmpl > $LOGROTATEDIR/opengnsysRepo
1070                fi
1071        fi
1072}
1073
1074# Resumen de actualización.
1075function updateSummary()
1076{
1077        # Actualizar fichero de versión y revisión.
1078        local VERSIONFILE REVISION
1079        VERSIONFILE="$INSTALL_TARGET/doc/VERSION.json"
1080        # Obtener revisión.
1081        if [ $REMOTE -eq 1 ]; then
1082                # Revisión: rAñoMesDía.Gitcommit (8 caracteres de fecha y 7 primeros de commit).
1083                REVISION=$(curl -s "$API_URL" | jq '"r" + (.commit.commit.committer.date | split("-") | join("")[:8]) + "." + (.commit.sha[:7])')
1084        else
1085                # Parámetro "release" del fichero JSON.
1086                REVISION=$(jq -r '.release' $PROGRAMDIR/../doc/VERSION.json 2>/dev/null)
1087        fi
1088        [ -f $VERSIONFILE ] || echo '{ "project": "OpenGnsys" }' > $VERSIONFILE
1089        jq ".release=$REVISION" $VERSIONFILE | sponge $VERSIONFILE
1090        VERSION="$(jq -r '[.project, .version, .codename, .release] | join(" ")' $VERSIONFILE 2>/dev/null)"
1091        # Borrar antiguo fichero de versión.
1092        rm -f "${VERSIONFILE/json/txt}"
1093
1094        echo
1095        echoAndLog "OpenGnsys Update Summary"
1096        echo       "========================"
1097        echoAndLog "Project version:                  $VERSION"
1098        echoAndLog "Update log file:                  $LOG_FILE"
1099        if [ -n "$NEWFILES" ]; then
1100                echoAndLog "Check new config files:           $(echo $NEWFILES)"
1101        fi
1102        if [ -n "$NEWSERVICES" ]; then
1103                echoAndLog "New compiled services:            $(echo $NEWSERVICES)"
1104                # Indicar si se debe reiniciar servicios manualmente o usando el Cron.
1105                [ -f /etc/default/opengnsys ] && source /etc/default/opengnsys
1106                if [ "$RUN_CRONJOB" == "no" ]; then
1107                        echoAndLog "        WARNING: you must to restart OpenGnsys services manually"
1108                else
1109                        echoAndLog "        New OpenGnsys services will be restarted by the cronjob"
1110                fi
1111        fi
1112        echoAndLog "Warnings:"
1113        echoAndLog " - You must to clear web browser cache before loading OpenGnsys page"
1114        echoAndLog " - Generated new key to access Repository REST API (file ogAdmRepo.cfg)"
1115        if [ -n "$CLIENTUPDATED" ]; then
1116                echoAndLog " - ogLive Client is updated to: $CLIENTUPDATED"
1117        fi
1118        if [ -n "$MYSQLCONFIG" ]; then
1119                echoAndLog " - MySQL must be reconfigured, run next code as DB root user and restart service:"
1120                echoAndLog "      $MYSQLCONFIG"
1121        fi
1122        echo
1123}
1124
1125
1126
1127#####################################################################
1128####### Proceso de actualización de OpenGnsys
1129#####################################################################
1130
1131
1132echoAndLog "OpenGnsys update begins at $(date)"
1133
1134pushd $WORKDIR
1135
1136# Comprobar si hay conexión y detectar parámetros de red por defecto.
1137checkNetworkConnection
1138if [ $? -ne 0 ]; then
1139        errorAndLog "Error connecting to server. Causes:"
1140        errorAndLog " - Network is unreachable, check device parameters"
1141        errorAndLog " - You are inside a private network, configure the proxy service"
1142        errorAndLog " - Server is temporally down, try again later"
1143        exit 1
1144fi
1145getNetworkSettings
1146
1147# Comprobar si se intanta actualizar a una versión anterior.
1148checkVersion
1149if [ $? -ne 0 ]; then
1150        errorAndLog "Cannot downgrade to an older version ($OLDVERSION to $NEWVERSION)"
1151        errorAndLog "You must to uninstall OpenGnsys and install desired release"
1152        exit 1
1153fi
1154
1155# Comprobar auto-actualización del programa.
1156if [ "$PROGRAMDIR" != "$INSTALL_TARGET/bin" ]; then
1157        checkAutoUpdate
1158        if [ $? -ne 0 ]; then
1159                echoAndLog "OpenGnsys updater has been overwritten"
1160                echoAndLog "Please, rerun this script"
1161                exit
1162        fi
1163fi
1164
1165# Detectar datos de auto-configuración del instalador.
1166autoConfigure
1167
1168# Instalar dependencias.
1169installDependencies ${DEPENDENCIES[*]}
1170if [ $? -ne 0 ]; then
1171        errorAndLog "Error: you must to install all needed dependencies"
1172        exit 1
1173fi
1174
1175# Arbol de directorios de OpenGnsys.
1176createDirs ${INSTALL_TARGET}
1177if [ $? -ne 0 ]; then
1178        errorAndLog "Error while creating directory paths"
1179        exit 1
1180fi
1181
1182# Si es necesario, descarga el repositorio de código en directorio temporal
1183if [ $REMOTE -eq 1 ]; then
1184        downloadCode $CODE_URL
1185        if [ $? -ne 0 ]; then
1186                errorAndLog "Error while getting code from repository"
1187                exit 1
1188        fi
1189else
1190        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
1191fi
1192
1193# Comprobar configuración de MySQL.
1194checkMysqlConfig $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD
1195
1196# Actualizar la BD.
1197updateDatabase
1198
1199# Actualizar ficheros complementarios del servidor
1200updateServerFiles
1201if [ $? -ne 0 ]; then
1202        errorAndLog "Error updating OpenGnsys Server files"
1203        exit 1
1204fi
1205
1206# Configurar Rsync.
1207rsyncConfigure
1208
1209# Actualizar ficheros del cliente
1210updateClientFiles
1211updateInterfaceAdm
1212
1213# Actualizar páqinas web
1214apacheConfiguration
1215updateWebFiles
1216if [ $? -ne 0 ]; then
1217        errorAndLog "Error updating OpenGnsys Web Admin files"
1218        exit 1
1219fi
1220# Actaulizar ficheros descargables.
1221updateDownloadableFiles
1222# Generar páginas Doxygen para instalar en el web
1223makeDoxygenFiles
1224
1225# Recompilar y actualizar los servicios del sistema
1226compileServices
1227
1228# Actaulizar ficheros auxiliares del cliente
1229updateClient
1230if [ $? -ne 0 ]; then
1231        errorAndLog "Error updating client files"
1232        exit 1
1233fi
1234
1235# Comprobar permisos y ficheros.
1236checkFiles
1237
1238# Mostrar resumen de actualización.
1239updateSummary
1240
1241rm -rf $WORKDIR
1242echoAndLog "OpenGnsys update finished at $(date)"
1243
1244popd
1245
Note: See TracBrowser for help on using the repository browser.