source: installer/opengnsys_update.sh @ 59e0a94

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacionwebconsole3
Last change on this file since 59e0a94 was 739fb00, checked in by ramon <ramongomez@…>, 13 years ago

Versión 1.0.3, #410: aplicar soluciones de la versión 1.0.2a en instalador y actualizador de la versión 1.0.3

git-svn-id: https://opengnsys.es/svn/branches/version1.0@2447 a21b9725-9963-47de-94b9-378ad31fedc9

  • Property mode set to 100755
File size: 22.9 KB
Line 
1#!/bin/bash
2#/**
3#@file    opengnsys_update.sh
4#@brief   Script actualización de OpenGnSys
5#@warning No se actualiza BD, ni ficheros de configuración.
6#@version 0.9 - basado en opengnsys_installer.sh
7#@author  Ramón Gómez - ETSII Univ. Sevilla
8#@date    2010/01/27
9#@version 1.0 - adaptación a OpenGnSys 1.0
10#@author  Ramón Gómez - ETSII Univ. Sevilla
11#@date    2011/03/02
12#@version 1.0.1 - control de auto actualización del script
13#@author  Ramón Gómez - ETSII Univ. Sevilla
14#@date    2011/05/17
15#@version 1.0.2a - obtiene valor de dirección IP por defecto
16#@author  Ramón Gómez - ETSII Univ. Sevilla
17#@date    2012/01/18
18#*/
19
20
21####  AVISO: Editar configuración de acceso por defecto a la Base de Datos.
22OPENGNSYS_DATABASE="ogAdmBD"            # Nombre de la base datos
23OPENGNSYS_DBUSER="usuog"                # Usuario de acceso
24OPENGNSYS_DBPASSWORD="passusuog"        # Clave del usuario
25
26####  AVISO: NO Editar variables de acceso desde el cliente
27OPENGNSYS_CLIENTUSER="opengnsys"        # Usuario Samba
28
29
30# Sólo ejecutable por usuario root
31if [ "$(whoami)" != 'root' ]; then
32        echo "ERROR: this program must run under root privileges!!"
33        exit 1
34fi
35# Error si OpenGnSys no está instalado (no existe el directorio del proyecto)
36INSTALL_TARGET=/opt/opengnsys
37if [ ! -d $INSTALL_TARGET ]; then
38        echo "ERROR: OpenGnSys is not installed, cannot update!!"
39        exit 1
40fi
41
42# Comprobar si se ha descargado el paquete comprimido (USESVN=0) o sólo el instalador (USESVN=1).
43PROGRAMDIR=$(readlink -e $(dirname "$0"))
44PROGRAMNAME=$(basename "$0")
45DEPS="build-essential g++-multilib rsync ctorrent samba unzip netpipes debootstrap schroot squashfs-tools"
46OPENGNSYS_SERVER="www.opengnsys.es"
47if [ -d "$PROGRAMDIR/../installer" ]; then
48        USESVN=0
49else
50        USESVN=1
51        DEPS="$DEPS subversion"
52fi
53SVN_URL="http://$OPENGNSYS_SERVER/svn/branches/version1.0/"
54
55WORKDIR=/tmp/opengnsys_update
56mkdir -p $WORKDIR
57
58LOG_FILE=/tmp/opengnsys_update.log
59
60
61
62#####################################################################
63####### Algunas funciones útiles de propósito general:
64#####################################################################
65
66# Comprobar auto-actualización.
67function checkAutoUpdate()
68{
69        local update=0
70
71        # Actaulizar el script si ha cambiado o no existe el original.
72        if [ $USESVN -eq 1 ]; then
73                svn export $SVN_URL/installer/$PROGRAMNAME
74                if ! diff --brief $PROGRAMNAME $INSTALL_TARGET/lib/$PROGRAMNAME &>/dev/null || ! test -f $INSTALL_TARGET/lib/$PROGRAMNAME; then
75                        mv $PROGRAMNAME $INSTALL_TARGET/lib
76                        update=1
77                else
78                        rm -f $PROGRAMNAME
79                fi
80        else
81                if ! diff --brief $PROGRAMDIR/$PROGRAMNAME $INSTALL_TARGET/lib/$PROGRAMNAME &>/dev/null || ! test -f $INSTALL_TARGET/lib/$PROGRAMNAME; then
82                        cp -a $PROGRAMDIR/$PROGRAMNAME $INSTALL_TARGET/lib
83                        update=1
84                fi
85        fi
86
87        return $update
88}
89
90
91function getDateTime()
92{
93        date "+%Y%m%d-%H%M%S"
94}
95
96# Escribe a fichero y muestra por pantalla
97function echoAndLog()
98{
99        echo $1
100        DATETIME=`getDateTime`
101        echo "$DATETIME;$SSH_CLIENT;$1" >> $LOG_FILE
102}
103
104function errorAndLog()
105{
106        echo "ERROR: $1"
107        DATETIME=`getDateTime`
108        echo "$DATETIME;$SSH_CLIENT;ERROR: $1" >> $LOG_FILE
109}
110
111
112#####################################################################
113####### Funciones de copia de seguridad y restauración de ficheros
114#####################################################################
115
116# Hace un backup del fichero pasado por parámetro
117# deja un -last y uno para el día
118function backupFile()
119{
120        if [ $# -ne 1 ]; then
121                errorAndLog "${FUNCNAME}(): invalid number of parameters"
122                exit 1
123        fi
124
125        local fichero=$1
126        local fecha=`date +%Y%m%d`
127
128        if [ ! -f $fichero ]; then
129                errorAndLog "${FUNCNAME}(): file $fichero doesn't exists"
130                return 1
131        fi
132
133        echoAndLog "${FUNCNAME}(): Making $fichero back-up"
134
135        # realiza una copia de la última configuración como last
136        cp -a $fichero "${fichero}-LAST"
137
138        # si para el día no hay backup lo hace, sino no
139        if [ ! -f "${fichero}-${fecha}" ]; then
140                cp -a $fichero "${fichero}-${fecha}"
141        fi
142}
143
144# Restaura un fichero desde su copia de seguridad
145function restoreFile()
146{
147        if [ $# -ne 1 ]; then
148                errorAndLog "${FUNCNAME}(): invalid number of parameters"
149                exit 1
150        fi
151
152        local fichero=$1
153
154        echoAndLog "${FUNCNAME}(): restoring file $fichero"
155        if [ -f "${fichero}-LAST" ]; then
156                cp -a "$fichero-LAST" "$fichero"
157        fi
158}
159
160
161#####################################################################
162####### Funciones de acceso a base de datos
163#####################################################################
164
165# Actualizar la base datos
166function importSqlFile()
167{
168        if [ $# -ne 4 ]; then
169                errorAndLog "${FNCNAME}(): invalid number of parameters"
170                exit 1
171        fi
172
173        local dbuser="$1"
174        local dbpassword="$2"
175        local database="$3"
176        local sqlfile="$4"
177        local tmpfile=$(mktemp)
178        local status
179
180        if [ ! -r $sqlfile ]; then
181                errorAndLog "${FUNCNAME}(): Unable to read $sqlfile!!"
182                return 1
183        fi
184
185        echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..."
186        chmod 600 $tmpfile
187        sed -e "s/SERVERIP/$SERVERIP/g" -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
188            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" $sqlfile > $tmpfile
189        mysql -u$dbuser -p"$dbpassword" --default-character-set=utf8 "$database" < $tmpfile
190        status=$?
191        rm -f $tmpfile
192        if [ $status -ne 0 ]; then
193                errorAndLog "${FUNCNAME}(): error importing $sqlfile in database $database"
194                return 1
195        fi
196        echoAndLog "${FUNCNAME}(): file imported to database $database"
197        return 0
198}
199
200
201#####################################################################
202####### Funciones de instalación de paquetes
203#####################################################################
204
205# Instalar las deependencias necesarias para el actualizador.
206function installDependencies()
207{
208        if [ $# = 0 ]; then
209                echoAndLog "${FUNCNAME}(): no deps needed."
210        else
211                while [ $# -gt 0 ]; do
212                        dpkg -s $1 2>/dev/null | grep -q "Status: install ok"
213                        if [ $? -ne 0 ]; then
214                                INSTALLDEPS="$INSTALLDEPS $1"
215                        fi
216                        shift
217                done
218                if [ -n "$INSTALLDEPS" ]; then
219                        apt-get update && apt-get -y install --force-yes $INSTALLDEPS
220                        if [ $? -ne 0 ]; then
221                                errorAndLog "${FUNCNAME}(): cannot install some dependencies: $INSTALLDEPS."
222                                return 1
223                        fi
224                fi
225        fi
226}
227
228
229#####################################################################
230####### Funciones para el manejo de Subversion
231#####################################################################
232
233function svnExportCode()
234{
235        if [ $# -ne 1 ]; then
236                errorAndLog "${FUNCNAME}(): invalid number of parameters"
237                exit 1
238        fi
239
240        local url="$1"
241
242        echoAndLog "${FUNCNAME}(): downloading subversion code..."
243
244        svn checkout "${url}" opengnsys
245        if [ $? -ne 0 ]; then
246                errorAndLog "${FUNCNAME}(): error getting code from ${url}, verify your user and password"
247                return 1
248        fi
249        echoAndLog "${FUNCNAME}(): subversion code downloaded"
250        return 0
251}
252
253
254############################################################
255###  Detectar red
256############################################################
257
258# Comprobar si existe conexión.
259function checkNetworkConnection()
260{
261        OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"www.opengnsys.es"}
262        wget --spider -q $OPENGNSYS_SERVER
263}
264
265# Obtener los parámetros de red del servidor.
266function getNetworkSettings()
267{
268        # Variables globales definidas:
269        # - SERVERIP:   IP local de la interfaz por defecto.
270
271        local DEVICES
272        local dev
273
274        echoAndLog "${FUNCNAME}(): Detecting network parameters."
275        DEVICES="$(ip -o link show up | awk '!/loopback/ {sub(/:.*/,"",$2); print $2}')"
276        for dev in $DEVICES; do
277                [ -z "$SERVERIP" ] && SERVERIP=$(ip -o addr show dev $dev | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4)}')
278        done
279}
280
281
282#####################################################################
283####### Funciones específicas de la instalación de Opengnsys
284#####################################################################
285
286# Actualizar cliente OpenGnSys
287function updateClientFiles()
288{
289        echoAndLog "${FUNCNAME}(): Updating OpenGnSys Client files."
290        rsync --exclude .svn -irplt $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
291        if [ $? -ne 0 ]; then
292                errorAndLog "${FUNCNAME}(): error while updating client structure"
293                exit 1
294        fi
295        find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null
296       
297        echoAndLog "${FUNCNAME}(): Updating OpenGnSys Cloning Engine files."
298        rsync --exclude .svn -irplt $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
299        if [ $? -ne 0 ]; then
300                errorAndLog "${FUNCNAME}(): error while updating engine files"
301                exit 1
302        fi
303       
304        echoAndLog "${FUNCNAME}(): client files update success."
305}
306
307# Configurar HTTPS y exportar usuario y grupo del servicio Apache.
308function apacheConfiguration ()
309{
310        local APACHECONF=/etc/apache2
311
312        # Activar HTTPS, si es necesario.
313        if [ -e $APACHECONF/sites-available/opengnsys.conf ]; then
314                echoAndLog "${FUNCNAME}(): Configuring HTTPS access..."
315                mv $APACHECONF/sites-available/opengnsys.conf $APACHECONF/sites-available/opengnsys
316                a2ensite default-ssl
317                a2enmod ssl
318                a2dissite opengnsys.conf
319                a2ensite opengnsys
320                /etc/init.d/apache2 restart
321        fi
322
323        # Variables de ejecución de Apache.
324        # - APACHE_RUN_USER
325        # - APACHE_RUN_GROUP
326        if [ -f $APACHECONF/envvars ]; then
327                source $APACHECONF/envvars
328        fi
329        APACHE_RUN_USER=${APACHE_RUN_USER:-"www-data"}
330        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"www-data"}
331}
332
333# Copiar ficheros del OpenGnSys Web Console.
334function updateWebFiles()
335{
336        local ERRCODE
337        echoAndLog "${FUNCNAME}(): Updating web files..."
338        backupFile $INSTALL_TARGET/www/controlacceso.php
339        mv $INSTALL_TARGET/www $INSTALL_TARGET/WebConsole
340        rsync --exclude .svn -irplt $WORKDIR/opengnsys/admin/WebConsole $INSTALL_TARGET
341        ERRCODE=$?
342        mv $INSTALL_TARGET/WebConsole $INSTALL_TARGET/www
343        unzip -o $WORKDIR/opengnsys/admin/xajax_0.5_standard.zip -d $INSTALL_TARGET/www/xajax
344        if [ $ERRCODE != 0 ]; then
345                errorAndLog "${FUNCNAME}(): Error updating web files."
346                exit 1
347        fi
348        restoreFile $INSTALL_TARGET/www/controlacceso.php
349        # Cambiar permisos para ficheros especiales.
350        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/includes $INSTALL_TARGET/www/images/iconos
351        echoAndLog "${FUNCNAME}(): Web files updated successfully."
352}
353
354# Copiar carpeta de Interface
355function updateInterfaceAdm()
356{
357        local errcode=0
358         
359        # Crear carpeta y copiar Interface
360        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
361        mv $INSTALL_TARGET/client/interfaceAdm $INSTALL_TARGET/client/Interface
362        rsync --exclude .svn -irplt $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client
363        errcoce=$?
364        mv $INSTALL_TARGET/client/Interface $INSTALL_TARGET/client/interfaceAdm
365        if [ $errcode -ne 0 ]; then
366                echoAndLog "${FUNCNAME}(): error while updating admin interface"
367                exit 1
368        fi
369        chmod -R +x $INSTALL_TARGET/client/interfaceAdm
370        chown $OPENGNSYS_CLIENTUSER:$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
371        chmod 700 $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
372        echoAndLog "${FUNCNAME}(): Admin interface updated successfully."
373}
374
375# Crear documentación Doxygen para la consola web.
376function makeDoxygenFiles()
377{
378        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
379        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
380                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
381        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
382                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
383                return 1
384        fi
385        rm -fr "$INSTALL_TARGET/www/api"
386        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
387        rm -fr $INSTALL_TARGET/www/{man,perlmod,rtf}
388        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/api
389        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
390}
391
392
393# Crea la estructura base de la instalación de opengnsys
394function createDirs()
395{
396        # Crear estructura de directorios.
397        echoAndLog "${FUNCNAME}(): creating directory paths in ${INSTALL_TARGET}"
398        mkdir -p ${INSTALL_TARGET}/{bin,doc,etc,lib,sbin,www}
399        mkdir -p ${INSTALL_TARGET}/{client,images}
400        mkdir -p ${INSTALL_TARGET}/log/clients
401        ln -fs ${INSTALL_TARGET}/log /var/log/opengnsys
402        ln -fs /var/lib/tftpboot ${INSTALL_TARGET}
403        mkdir -p ${INSTALL_TARGET}/tftpboot/{pxelinux.cfg,menu.lst}
404        if [ $? -ne 0 ]; then
405                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
406                return 1
407        fi
408
409        # Crear usuario ficticio.
410        if id -u $OPENGNSYS_CLIENTUSER &>/dev/null; then
411                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENTUSER\" is already created"
412        else
413                echoAndLog "${FUNCNAME}(): creating OpenGnSys user"
414                useradd $OPENGNSYS_CLIENTUSER 2>/dev/null
415                if [ $? -ne 0 ]; then
416                        errorAndLog "${FUNCNAME}(): error creating OpenGnSys user"
417                        return 1
418                fi
419        fi
420
421        # Establecer los permisos básicos.
422        echoAndLog "${FUNCNAME}(): setting directory permissions"
423        chmod -R 775 $INSTALL_TARGET/{log/clients,images,tftpboot/pxelinux.cfg,tftpboot/menu.lst}
424        chown -R :$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/{log/clients,images,tftpboot/pxelinux.cfg,tftpboot/menu.lst}
425        if [ $? -ne 0 ]; then
426                errorAndLog "${FUNCNAME}(): error while setting permissions"
427                return 1
428        fi
429
430        echoAndLog "${FUNCNAME}(): directory paths created"
431        return 0
432}
433
434# Copia ficheros de configuración y ejecutables genéricos del servidor.
435function updateServerFiles()
436{
437        # No copiar ficheros del antiguo cliente Initrd
438        local SOURCES=( repoman/bin \
439                        server/bin \
440                        server/tftpboot \
441                        installer/opengnsys_uninstall.sh \
442                        doc )
443        local TARGETS=( bin \
444                        bin \
445                        tftpboot \
446                        lib/opengnsys_uninstall.sh \
447                        doc )
448
449        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
450                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
451                exit 1
452        fi
453
454        echoAndLog "${FUNCNAME}(): updating files in server directories"
455        pushd $WORKDIR/opengnsys >/dev/null
456        local i
457        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
458                if [ -d "$INSTALL_TARGET/${TARGETS[i]}" ]; then
459                        rsync --exclude .svn -irplt "${SOURCES[i]}" $(dirname $(readlink -e "$INSTALL_TARGET/${TARGETS[i]}"))
460                else
461                        rsync --exclude .svn -irplt "${SOURCES[i]}" $(readlink -e "$INSTALL_TARGET/${TARGETS[i]}")
462                fi
463        done
464        popd >/dev/null
465        NEWFILES=""             # Ficheros de configuración que han cambiado de formato.
466        if grep -q 'pxelinux.0' /etc/dhcp*/dhcpd*.conf; then
467                echoAndLog "${FUNCNAME}(): updating DHCP files"
468                perl -pi -e 's/pxelinux.0/grldr/' /etc/dhcp*/dhcpd*.conf
469                for i in isc-dhcp-server dhcpd3-server dhcpd; do
470                        [ -f /etc/init.d/$i ] && /etc/init.d/$i restart
471                done
472                NEWFILES="/etc/dhcp*/dhcpd*.conf"
473        fi
474        if ! diff --quiet $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys 2>/dev/null; then
475                echoAndLog "${FUNCNAME}(): updating new init file"
476                backupFile /etc/init.d/opengnsys
477                cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
478                NEWFILES="$NEWFILES /etc/init.d/opengnsys"
479        fi
480        if grep -q "UrlMsg=.*msgbrowser.php" $INSTALL_TARGET/client/etc/ogAdmClient.cfg 2>/dev/null; then
481                echoAndLog "${FUNCNAME}(): updating new client config file"
482                backupFile $INSTALL_TARGET/client/etc/ogAdmClient.cfg
483                perl -pi -e 's!UrlMsg=.*msgbrowser\.php!UrlMsg=http://localhost/cgi-bin/httpd-log\.sh!g' $INSTALL_TARGET/client/etc/ogAdmClient.cfg
484                NEWFILES="$NEWFILES $INSTALL_TARGET/client/etc/ogAdmClient.cfg"
485        fi
486        echoAndLog "${FUNCNAME}(): updating cron files"
487        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
488        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
489        echoAndLog "${FUNCNAME}(): server files updated successfully."
490}
491
492####################################################################
493### Funciones de compilación de código fuente de servicios
494####################################################################
495
496# Recompilar y actualiza los serivicios y clientes.
497function compileServices()
498{
499        local hayErrores=0
500
501        # Compilar OpenGnSys Server
502        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Admin Server"
503        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
504        make && mv ogAdmServer $INSTALL_TARGET/sbin
505        if [ $? -ne 0 ]; then
506                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Admin Server"
507                hayErrores=1
508        fi
509        popd
510        # Compilar OpenGnSys Repository Manager
511        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Repository Manager"
512        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo
513        make && mv ogAdmRepo $INSTALL_TARGET/sbin
514        if [ $? -ne 0 ]; then
515                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Repository Manager"
516                hayErrores=1
517        fi
518        popd
519        # Compilar OpenGnSys Agent
520        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Agent"
521        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
522        make && mv ogAdmAgent $INSTALL_TARGET/sbin
523        if [ $? -ne 0 ]; then
524                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Agent"
525                hayErrores=1
526        fi
527        popd
528
529        # Compilar OpenGnSys Client
530        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Client"
531        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
532        make && mv ogAdmClient $INSTALL_TARGET/client/bin
533        if [ $? -ne 0 ]; then
534                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Client"
535                hayErrores=1
536        fi
537        popd
538
539        return $hayErrores
540}
541
542
543####################################################################
544### Funciones instalacion cliente OpenGnSys
545####################################################################
546
547# Actualizar nuevo cliente para OpenGnSys 1.0
548function updateClient()
549{
550        local DOWNLOADURL="http://$OPENGNSYS_SERVER/downloads"
551        local FILENAME=ogLive-oneiric-3.0.0-14-generic-r2439.iso
552        local SOURCEFILE=$DOWNLOADURL/$FILENAME
553        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
554        local SOURCELENGTH
555        local TARGETLENGTH
556        local TMPDIR=/tmp/${FILENAME%.iso}
557        local OGINITRD=$INSTALL_TARGET/tftpboot/ogclient/oginitrd.img
558        local SAMBAPASS
559
560        # Comprobar si debe actualizarse el cliente.
561        SOURCELENGTH=$(LANG=C wget --spider $SOURCEFILE 2>&1 | awk '/Length:/ {print $2}')
562        TARGETLENGTH=$(ls -l $TARGETFILE 2>/dev/null | awk '{print $5}')
563        [ -z $TARGETLENGTH ] && TARGETLENGTH=0
564        if [ "$SOURCELENGTH" != "$TARGETLENGTH" ]; then
565                echoAndLog "${FUNCNAME}(): Loading Client"
566                wget $DOWNLOADURL/$FILENAME -O $TARGETFILE
567                if [ ! -s $TARGETFILE ]; then
568                        errorAndLog "${FUNCNAME}(): Error loading OpenGnSys Client"
569                        return 1
570                fi
571                # Obtener la clave actual de acceso a Samba para restaurarla.
572                if [ -f $OGINITRD ]; then
573                        SAMBAPASS=$(gzip -dc $OGINITRD | \
574                                    cpio -i --to-stdout scripts/ogfunctions 2>&1 | \
575                                    grep "^[    ]*OPTIONS=" | \
576                                    sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
577                fi
578                # Montar la imagen ISO del ogclient, actualizar ficheros y desmontar.
579                echoAndLog "${FUNCNAME}(): Updatting ogclient files"
580                mkdir -p $TMPDIR
581                mount -o loop,ro $TARGETFILE $TMPDIR
582                rsync -irlt $TMPDIR/ogclient $INSTALL_TARGET/tftpboot
583                umount $TMPDIR
584                rmdir $TMPDIR
585                # Recuperar la clave de acceso a Samba.
586                if [ -n "$SAMBAPASS" ]; then
587                        echoAndLog "${FUNCNAME}(): Restoring client access key"
588                        echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | \
589                                        $INSTALL_TARGET/bin/setsmbpass
590                fi
591                # Establecer los permisos.
592                find -L $INSTALL_TARGET/tftpboot -type d -exec chmod 755 {} \;
593                find -L $INSTALL_TARGET/tftpboot -type f -exec chmod 644 {} \;
594                chown -R :$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/tftpboot/ogclient
595                chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/tftpboot/{menu.lst,pxelinux.cfg}
596               
597                # Ofrecer md5 del kernel y vmlinuz para ogupdateinitrd en cache
598                cp -arv $INSTALL_TARGET/tftpboot/ogclient/ogvmlinuz* $INSTALL_TARGET/tftpboot
599                cp -arv $INSTALL_TARGET/tftpboot/ogclient/oginitrd.img* $INSTALL_TARGET/tftpboot
600               
601                echoAndLog "${FUNCNAME}(): Client update successfully"
602        else
603                echoAndLog "${FUNCNAME}(): Client is already updated"
604        fi
605}
606
607# Resumen de actualización.
608function updateSummary()
609{
610        # Actualizar fichero de versión y revisión.
611        local VERSIONFILE="$INSTALL_TARGET/doc/VERSION.txt"
612        local REVISION=$(LANG=C svn info $SVN_URL|awk '/Revision:/ {print "r"$2}')
613
614        [ -f $VERSIONFILE ] || echo "OpenGnSys" >$VERSIONFILE
615        perl -pi -e "s/($| r[0-9]*)/ $REVISION/" $VERSIONFILE
616
617        echo
618        echoAndLog "OpenGnSys Update Summary"
619        echo       "========================"
620        echoAndLog "Project version:                  $(cat $VERSIONFILE)"
621        if [ -n "$NEWFILES" ]; then
622                echoAndLog "Check the new config files:       $(echo $NEWFILES)"
623        fi
624        echo
625}
626
627
628
629#####################################################################
630####### Proceso de actualización de OpenGnSys
631#####################################################################
632
633
634echoAndLog "OpenGnSys update begins at $(date)"
635
636pushd $WORKDIR
637
638# Comprobar si hay conexión y detectar parámetros de red por defecto.
639checkNetworkConnection
640if [ $? -ne 0 ]; then
641        errorAndLog "Error connecting to server. Causes:"
642        errorAndLog " - Network is unreachable, review devices parameters."
643        errorAndLog " - You are inside a private network, configure the proxy service."
644        errorAndLog " - Server is temporally down, try agian later."
645        exit 1
646fi
647getNetworkSettings
648
649# Comprobar auto-actualización del programa.
650if [ "$PROGRAMDIR" != "$INSTALL_TARGET/bin" ]; then
651        checkAutoUpdate
652        if [ $? -ne 0 ]; then
653                echoAndLog "OpenGnSys updater has been overwritten."
654                echoAndLog "Please, re-execute this script."
655                exit
656        fi
657fi
658
659# Instalar dependencias.
660installDependencies $DEPS
661if [ $? -ne 0 ]; then
662        errorAndLog "Error: you may install all needed dependencies."
663        exit 1
664fi
665
666# Arbol de directorios de OpenGnSys.
667createDirs ${INSTALL_TARGET}
668if [ $? -ne 0 ]; then
669        errorAndLog "Error while creating directory paths!"
670        exit 1
671fi
672
673# Si es necesario, descarga el repositorio de código en directorio temporal
674if [ $USESVN -eq 1 ]; then
675        svnExportCode $SVN_URL
676        if [ $? -ne 0 ]; then
677                errorAndLog "Error while getting code from svn"
678                exit 1
679        fi
680else
681        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
682fi
683
684# Si existe fichero de actualización de la base de datos; aplicar cambios.
685INSTVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt)
686REPOVERSION=$(awk '{print $2}' $WORKDIR/opengnsys/doc/VERSION.txt)
687OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
688if [ -f $OPENGNSYS_DBUPDATEFILE ]; then
689        echoAndLog "Updating tables from version $INSTVERSION to $REPOVERSION"
690        importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $OPENGNSYS_DBUPDATEFILE
691else
692        echoAndLog "Database unchanged."
693fi
694
695# Actualizar ficheros complementarios del servidor
696updateServerFiles
697if [ $? -ne 0 ]; then
698        errorAndLog "Error updating OpenGnSys Server files"
699        exit 1
700fi
701
702# Actualizar ficheros del cliente
703updateClientFiles
704updateInterfaceAdm
705
706# Actualizar páqinas web
707apacheConfiguration
708updateWebFiles
709if [ $? -ne 0 ]; then
710        errorAndLog "Error updating OpenGnSys Web Admin files"
711        exit 1
712fi
713# Generar páginas Doxygen para instalar en el web
714makeDoxygenFiles
715
716# Recompilar y actualizar los servicios del sistema
717compileServices
718
719# Actaulizar ficheros auxiliares del cliente
720updateClient
721if [ $? -ne 0 ]; then
722        errorAndLog "Error updating clients"
723        exit 1
724fi
725
726# Eliminamos el fichero de estado del tracker porque es incompatible entre los distintos paquetes
727if [ -f /tmp/dstate ]; then
728        rm -f /tmp/dstate
729fi
730
731# Mostrar resumen de actualización.
732updateSummary
733
734#rm -rf $WORKDIR
735echoAndLog "OpenGnSys update finished at $(date)"
736
737popd
738
Note: See TracBrowser for help on using the repository browser.