source: installer/opengnsys_update.sh @ 547d804b

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 547d804b was e262ce7, checked in by ramon <ramongomez@…>, 12 years ago

Versión 1.0.5, #569: Corregir erratas al aplicar actualización de la base de datos.

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

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