source: installer/opengnsys_update.sh @ 97b8472

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

#784: Fixing Apache configuration error when multiple instances of PHP-FPM are installed.

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