source: installer/opengnsys_update.sh @ ca0f67c6

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 ca0f67c6 was 11b812d, checked in by ramon <ramongomez@…>, 12 years ago

#565 Instalardor y actualizador incluyen paquete para crear sistema de fichero para imagen diferencial.

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

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