source: installer/opengnsys_update.sh @ b4c5de3

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 b4c5de3 was 7bb72f7, checked in by ramon <ramongomez@…>, 13 years ago

Versión 1.0.3, #414: Actaulizador detecta directorio de TFTP en Debian 6.

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

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