source: installer/opengnsys_update.sh @ 6903f32

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 6903f32 was 56f100f, checked in by ramon <ramongomez@…>, 13 years ago

Versión 1.0.4, #513 #527: Corregir algunas erratas.

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

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