source: installer/opengnsys_update.sh @ 4af842a

opengnsys-1.1.0
Last change on this file since 4af842a was 2530022, checked in by ramon <ramongomez@…>, 7 years ago

#730: Corrección en URL de actualización y en librerías ignoradas.

git-svn-id: https://opengnsys.es/svn/tags/opengnsys-1.1.0@5608 a21b9725-9963-47de-94b9-378ad31fedc9

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