source: installer/opengnsys_update.sh @ 560358b

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-instalacion
Last change on this file since 560358b was d986707, checked in by Ramón M. Gómez <ramongomez@…>, 5 years ago

#915: Add new ogAdmServer compilation dependency.

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