source: installer/opengnsys_update.sh @ 35f55cb

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 35f55cb was 7669bca, checked in by ramon <ramongomez@…>, 12 years ago

Versión 1.0.5, #562. Instalador y actualizador protegen su fichero de log, porque puede contener información sensible.

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

  • Property mode set to 100755
File size: 25.9 KB
Line 
1#!/bin/bash
2#/**
3#@file    opengnsys_update.sh
4#@brief   Script actualización de OpenGnSys
5#@warning No se actualiza BD, ni ficheros de configuración.
6#@version 0.9 - basado en opengnsys_installer.sh
7#@author  Ramón Gómez - ETSII Univ. Sevilla
8#@date    2010/01/27
9#@version 1.0 - adaptación a OpenGnSys 1.0
10#@author  Ramón Gómez - ETSII Univ. Sevilla
11#@date    2011/03/02
12#@version 1.0.1 - control de auto actualización del script
13#@author  Ramón Gómez - ETSII Univ. Sevilla
14#@date    2011/05/17
15#@version 1.0.2a - obtiene valor de dirección IP por defecto
16#@author  Ramón Gómez - ETSII Univ. Sevilla
17#@date    2012/01/18
18#@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
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 )
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 )
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 status
239
240        if [ ! -r $sqlfile ]; then
241                errorAndLog "${FUNCNAME}(): Unable to read $sqlfile!!"
242                return 1
243        fi
244
245        echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..."
246        chmod 600 $tmpfile
247        sed -e "s/SERVERIP/$SERVERIP/g" -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
248            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" $sqlfile > $tmpfile
249        mysql -u$dbuser -p"$dbpassword" --default-character-set=utf8 -D "$database" < $tmpfile
250        status=$?
251        rm -f $tmpfile
252        if [ $status -ne 0 ]; then
253                errorAndLog "${FUNCNAME}(): error importing $sqlfile in database $database"
254                return 1
255        fi
256        echoAndLog "${FUNCNAME}(): file imported to database $database"
257        return 0
258}
259
260
261#####################################################################
262####### Funciones de instalación de paquetes
263#####################################################################
264
265# Instalar las deependencias necesarias para el actualizador.
266function installDependencies()
267{
268        local package
269
270        if [ $# = 0 ]; then
271                echoAndLog "${FUNCNAME}(): no deps needed."
272        else
273                while [ $# -gt 0 ]; do
274                        package="$1"
275                        eval $CHECKPKG || INSTALLDEPS="$INSTALLDEPS $1"
276                        shift
277                done
278                if [ -n "$INSTALLDEPS" ]; then
279                        $UPDATEPKGLIST
280                        $INSTALLPKGS $INSTALLDEPS
281                        if [ $? -ne 0 ]; then
282                                errorAndLog "${FUNCNAME}(): cannot install some dependencies: $INSTALLDEPS."
283                                return 1
284                        fi
285                fi
286        fi
287}
288
289
290#####################################################################
291####### Funciones para el manejo de Subversion
292#####################################################################
293
294function svnExportCode()
295{
296        if [ $# -ne 1 ]; then
297                errorAndLog "${FUNCNAME}(): invalid number of parameters"
298                exit 1
299        fi
300
301        local url="$1"
302
303        echoAndLog "${FUNCNAME}(): downloading subversion code..."
304
305        svn checkout "${url}" opengnsys
306        if [ $? -ne 0 ]; then
307                errorAndLog "${FUNCNAME}(): error getting code from ${url}, verify your user and password"
308                return 1
309        fi
310        echoAndLog "${FUNCNAME}(): subversion code downloaded"
311        return 0
312}
313
314
315############################################################
316###  Detectar red
317############################################################
318
319# Comprobar si existe conexión.
320function checkNetworkConnection()
321{
322        OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"www.opengnsys.es"}
323        wget --spider -q $OPENGNSYS_SERVER
324}
325
326# Obtener los parámetros de red del servidor.
327function getNetworkSettings()
328{
329        # Variables globales definidas:
330        # - SERVERIP:   IP local de la interfaz por defecto.
331
332        local DEVICES
333        local dev
334
335        echoAndLog "${FUNCNAME}(): Detecting network parameters."
336        DEVICES="$(ip -o link show up | awk '!/loopback/ {sub(/:.*/,"",$2); print $2}')"
337        for dev in $DEVICES; do
338                [ -z "$SERVERIP" ] && SERVERIP=$(ip -o addr show dev $dev | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4)}')
339        done
340}
341
342
343#####################################################################
344####### Funciones específicas de la instalación de Opengnsys
345#####################################################################
346
347# Actualizar cliente OpenGnSys
348function updateClientFiles()
349{
350        echoAndLog "${FUNCNAME}(): Updating OpenGnSys Client files."
351        rsync --exclude .svn -irplt $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
352        if [ $? -ne 0 ]; then
353                errorAndLog "${FUNCNAME}(): error while updating client structure"
354                exit 1
355        fi
356        find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null
357       
358        echoAndLog "${FUNCNAME}(): Updating OpenGnSys Cloning Engine files."
359        rsync --exclude .svn -irplt $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
360        if [ $? -ne 0 ]; then
361                errorAndLog "${FUNCNAME}(): error while updating engine files"
362                exit 1
363        fi
364       
365        echoAndLog "${FUNCNAME}(): client files update success."
366}
367
368# Configurar HTTPS y exportar usuario y grupo del servicio Apache.
369function apacheConfiguration ()
370{
371        # Activar HTTPS (solo actualizando desde versiones anteriores a 1.0.2).
372        if [ -e $APACHECFGDIR/sites-available/opengnsys.conf ]; then
373                echoAndLog "${FUNCNAME}(): Configuring HTTPS access..."
374                mv $APACHECFGDIR/sites-available/opengnsys.conf $APACHECFGDIR/sites-available/opengnsys
375                a2ensite default-ssl
376                a2enmod ssl
377                a2dissite opengnsys.conf
378                a2ensite opengnsys
379                $APACHESERV restart
380        fi
381
382        # Variables de ejecución de Apache.
383        # - APACHE_RUN_USER
384        # - APACHE_RUN_GROUP
385        if [ -f $APACHECFGDIR/envvars ]; then
386                source $APACHECFGDIR/envvars
387        fi
388        APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
389        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
390}
391
392# Copiar ficheros del OpenGnSys Web Console.
393function updateWebFiles()
394{
395        local ERRCODE
396        echoAndLog "${FUNCNAME}(): Updating web files..."
397        backupFile $INSTALL_TARGET/www/controlacceso.php
398        mv $INSTALL_TARGET/www $INSTALL_TARGET/WebConsole
399        rsync --exclude .svn -irplt $WORKDIR/opengnsys/admin/WebConsole $INSTALL_TARGET
400        ERRCODE=$?
401        mv $INSTALL_TARGET/WebConsole $INSTALL_TARGET/www
402        unzip -o $WORKDIR/opengnsys/admin/xajax_0.5_standard.zip -d $INSTALL_TARGET/www/xajax
403        if [ $ERRCODE != 0 ]; then
404                errorAndLog "${FUNCNAME}(): Error updating web files."
405                exit 1
406        fi
407        restoreFile $INSTALL_TARGET/www/controlacceso.php
408        # Cambiar permisos para ficheros especiales.
409        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/images/{fotos,iconos}
410        echoAndLog "${FUNCNAME}(): Web files updated successfully."
411}
412
413# Copiar carpeta de Interface
414function updateInterfaceAdm()
415{
416        local errcode=0
417         
418        # Crear carpeta y copiar Interface
419        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
420        mv $INSTALL_TARGET/client/interfaceAdm $INSTALL_TARGET/client/Interface
421        rsync --exclude .svn -irplt $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client
422        errcoce=$?
423        mv $INSTALL_TARGET/client/Interface $INSTALL_TARGET/client/interfaceAdm
424        if [ $errcode -ne 0 ]; then
425                echoAndLog "${FUNCNAME}(): error while updating admin interface"
426                exit 1
427        fi
428        chmod -R +x $INSTALL_TARGET/client/interfaceAdm
429        chown $OPENGNSYS_CLIENTUSER:$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
430        chmod 700 $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
431        echoAndLog "${FUNCNAME}(): Admin interface updated successfully."
432}
433
434# Crear documentación Doxygen para la consola web.
435function makeDoxygenFiles()
436{
437        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
438        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
439                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
440        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
441                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
442                return 1
443        fi
444        rm -fr "$INSTALL_TARGET/www/api"
445        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
446        rm -fr $INSTALL_TARGET/www/{man,perlmod,rtf}
447        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/api
448        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
449}
450
451
452# Crea la estructura base de la instalación de opengnsys
453function createDirs()
454{
455        # Crear estructura de directorios.
456        echoAndLog "${FUNCNAME}(): creating directory paths in ${INSTALL_TARGET}"
457        local dir
458
459        mkdir -p ${INSTALL_TARGET}/{bin,doc,etc,lib,sbin,www}
460        mkdir -p ${INSTALL_TARGET}/{client,images}
461        mkdir -p ${INSTALL_TARGET}/log/clients
462        ln -fs ${INSTALL_TARGET}/log /var/log/opengnsys
463        # Detectar directorio de instalación de TFTP.
464        if [ ! -L ${INSTALL_TARGET}/tftpboot ]; then
465                for dir in /var/lib/tftpboot /srv/tftp; do
466                        [ -d $dir ] && ln -fs $dir ${INSTALL_TARGET}/tftpboot
467                done
468        fi
469        mkdir -p ${INSTALL_TARGET}/tftpboot/{pxelinux.cfg,menu.lst}
470        if [ $? -ne 0 ]; then
471                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
472                return 1
473        fi
474
475        # Crear usuario ficticio.
476        if id -u $OPENGNSYS_CLIENTUSER &>/dev/null; then
477                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENTUSER\" is already created"
478        else
479                echoAndLog "${FUNCNAME}(): creating OpenGnSys user"
480                useradd $OPENGNSYS_CLIENTUSER 2>/dev/null
481                if [ $? -ne 0 ]; then
482                        errorAndLog "${FUNCNAME}(): error creating OpenGnSys user"
483                        return 1
484                fi
485        fi
486
487        # Establecer los permisos básicos.
488        echoAndLog "${FUNCNAME}(): setting directory permissions"
489        chmod -R 775 $INSTALL_TARGET/{log/clients,images,tftpboot/pxelinux.cfg,tftpboot/menu.lst}
490        chown -R :$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/{log/clients,images,tftpboot/pxelinux.cfg,tftpboot/menu.lst}
491        if [ $? -ne 0 ]; then
492                errorAndLog "${FUNCNAME}(): error while setting permissions"
493                return 1
494        fi
495
496        # Mover el fichero de registro al directorio de logs.
497        echoAndLog "${FUNCNAME}(): moving update log file"
498        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
499        chmod 600 $LOG_FILE
500
501        echoAndLog "${FUNCNAME}(): directory paths created"
502        return 0
503}
504
505# Copia ficheros de configuración y ejecutables genéricos del servidor.
506function updateServerFiles()
507{
508        # No copiar ficheros del antiguo cliente Initrd
509        local SOURCES=( repoman/bin \
510                        server/bin \
511                        server/tftpboot \
512                        installer/opengnsys_uninstall.sh \
513                        installer/install_ticket_wolunicast.sh \
514                        doc )
515        local TARGETS=( bin \
516                        bin \
517                        tftpboot \
518                        lib/opengnsys_uninstall.sh \
519                        lib/install_ticket_wolunicast.sh \
520                        doc )
521
522        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
523                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
524                exit 1
525        fi
526
527        echoAndLog "${FUNCNAME}(): updating files in server directories"
528        pushd $WORKDIR/opengnsys >/dev/null
529        local i
530        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
531                if [ -d "$INSTALL_TARGET/${TARGETS[i]}" ]; then
532                        rsync --exclude .svn -irplt "${SOURCES[i]}" $(dirname $(readlink -e "$INSTALL_TARGET/${TARGETS[i]}"))
533                else
534                        rsync -irplt "${SOURCES[i]}" $(readlink -m "$INSTALL_TARGET/${TARGETS[i]}")
535                fi
536        done
537        popd >/dev/null
538        NEWFILES=""             # Ficheros de configuración que han cambiado de formato.
539        if grep -q 'pxelinux.0' /etc/dhcp*/dhcpd*.conf; then
540                echoAndLog "${FUNCNAME}(): updating DHCP files"
541                perl -pi -e 's/pxelinux.0/grldr/' /etc/dhcp*/dhcpd*.conf
542                $DHCPSERV restart
543                NEWFILES="/etc/dhcp*/dhcpd*.conf"
544        fi
545        if ! diff -q $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys 2>/dev/null; then
546                echoAndLog "${FUNCNAME}(): updating new init file"
547                backupFile /etc/init.d/opengnsys
548                cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
549                NEWFILES="$NEWFILES /etc/init.d/opengnsys"
550        fi
551        if grep -q "UrlMsg=.*msgbrowser.php" $INSTALL_TARGET/client/etc/ogAdmClient.cfg 2>/dev/null; then
552                echoAndLog "${FUNCNAME}(): updating new client config file"
553                backupFile $INSTALL_TARGET/client/etc/ogAdmClient.cfg
554                perl -pi -e 's!UrlMsg=.*msgbrowser\.php!UrlMsg=http://localhost/cgi-bin/httpd-log\.sh!g' $INSTALL_TARGET/client/etc/ogAdmClient.cfg
555                NEWFILES="$NEWFILES $INSTALL_TARGET/client/etc/ogAdmClient.cfg"
556        fi
557        echoAndLog "${FUNCNAME}(): updating cron files"
558        [ ! -f /etc/cron.d/opengnsys ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
559        [ ! -f /etc/cron.d/torrentcreator ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
560        [ ! -f /etc/cron.d/torrenttracker ] && echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
561        echoAndLog "${FUNCNAME}(): server files updated successfully."
562}
563
564####################################################################
565### Funciones de compilación de código fuente de servicios
566####################################################################
567
568# Recompilar y actualiza los serivicios y clientes.
569function compileServices()
570{
571        local hayErrores=0
572
573        # Compilar OpenGnSys Server
574        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Admin Server"
575        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
576        make && mv ogAdmServer $INSTALL_TARGET/sbin
577        if [ $? -ne 0 ]; then
578                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Admin Server"
579                hayErrores=1
580        fi
581        popd
582        # Compilar OpenGnSys Repository Manager
583        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Repository Manager"
584        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo
585        make && mv ogAdmRepo $INSTALL_TARGET/sbin
586        if [ $? -ne 0 ]; then
587                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Repository Manager"
588                hayErrores=1
589        fi
590        popd
591        # Compilar OpenGnSys Agent
592        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Agent"
593        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
594        make && mv ogAdmAgent $INSTALL_TARGET/sbin
595        if [ $? -ne 0 ]; then
596                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Agent"
597                hayErrores=1
598        fi
599        popd
600
601        # Compilar OpenGnSys Client
602        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Client"
603        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
604        make && mv ogAdmClient $INSTALL_TARGET/client/bin
605        if [ $? -ne 0 ]; then
606                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Client"
607                hayErrores=1
608        fi
609        popd
610
611        return $hayErrores
612}
613
614
615####################################################################
616### Funciones instalacion cliente OpenGnSys
617####################################################################
618
619# Actualizar cliente OpenGnSys
620function updateClient()
621{
622        local DOWNLOADURL="http://$OPENGNSYS_SERVER/downloads"
623        #local FILENAME=ogLive-precise-3.2.0-23-generic-pae-r3017.iso   # 1.0.4-rc1
624        local FILENAME=ogLive-precise-3.2.0-23-generic-r3257.iso        # 1.0.4-rc2
625        local SOURCEFILE=$DOWNLOADURL/$FILENAME
626        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
627        local SOURCELENGTH
628        local TARGETLENGTH
629        local TMPDIR=/tmp/${FILENAME%.iso}
630        local OGINITRD=$INSTALL_TARGET/tftpboot/ogclient/oginitrd.img
631        local SAMBAPASS
632
633        # Comprobar si debe actualizarse el cliente.
634        SOURCELENGTH=$(LANG=C wget --spider $SOURCEFILE 2>&1 | awk '/Length:/ {print $2}')
635        TARGETLENGTH=$(ls -l $TARGETFILE 2>/dev/null | awk '{print $5}')
636        [ -z $TARGETLENGTH ] && TARGETLENGTH=0
637        if [ "$SOURCELENGTH" != "$TARGETLENGTH" ]; then
638                echoAndLog "${FUNCNAME}(): Loading Client"
639                wget $DOWNLOADURL/$FILENAME -O $TARGETFILE
640                if [ ! -s $TARGETFILE ]; then
641                        errorAndLog "${FUNCNAME}(): Error loading OpenGnSys Client"
642                        return 1
643                fi
644                # Obtener la clave actual de acceso a Samba para restaurarla.
645                if [ -f $OGINITRD ]; then
646                        SAMBAPASS=$(gzip -dc $OGINITRD | \
647                                    cpio -i --to-stdout scripts/ogfunctions 2>&1 | \
648                                    grep "^[    ]*OPTIONS=" | \
649                                    sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
650                fi
651                # Montar la imagen ISO del ogclient, actualizar ficheros y desmontar.
652                echoAndLog "${FUNCNAME}(): Updatting ogclient files"
653                mkdir -p $TMPDIR
654                mount -o loop,ro $TARGETFILE $TMPDIR
655                rsync -irlt $TMPDIR/ogclient $INSTALL_TARGET/tftpboot
656                umount $TMPDIR
657                rmdir $TMPDIR
658                # Recuperar la clave de acceso a Samba.
659                if [ -n "$SAMBAPASS" ]; then
660                        echoAndLog "${FUNCNAME}(): Restoring client access key"
661                        echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | \
662                                        $INSTALL_TARGET/bin/setsmbpass
663                fi
664                # Establecer los permisos.
665                find -L $INSTALL_TARGET/tftpboot -type d -exec chmod 755 {} \;
666                find -L $INSTALL_TARGET/tftpboot -type f -exec chmod 644 {} \;
667                chown -R :$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/tftpboot/ogclient
668                chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/tftpboot/{menu.lst,pxelinux.cfg}
669               
670                # Ofrecer md5 del kernel y vmlinuz para ogupdateinitrd en cache
671                cp -av $INSTALL_TARGET/tftpboot/ogclient/ogvmlinuz* $INSTALL_TARGET/tftpboot
672                cp -av $INSTALL_TARGET/tftpboot/ogclient/oginitrd.img* $INSTALL_TARGET/tftpboot
673               
674                echoAndLog "${FUNCNAME}(): Client update successfully"
675        else
676                echoAndLog "${FUNCNAME}(): Client is already updated"
677        fi
678}
679
680# Resumen de actualización.
681function updateSummary()
682{
683        # Actualizar fichero de versión y revisión.
684        local VERSIONFILE="$INSTALL_TARGET/doc/VERSION.txt"
685        local REVISION=$(LANG=C svn info $SVN_URL|awk '/Rev:/ {print "r"$4}')
686
687        [ -f $VERSIONFILE ] || echo "OpenGnSys" >$VERSIONFILE
688        perl -pi -e "s/($| r[0-9]*)/ $REVISION/" $VERSIONFILE
689
690        echo
691        echoAndLog "OpenGnSys Update Summary"
692        echo       "========================"
693        echoAndLog "Project version:                  $(cat $VERSIONFILE)"
694        echoAndLog "Update log file:                  $LOG_FILE"
695        if [ -n "$NEWFILES" ]; then
696                echoAndLog "Check the new config files:       $(echo $NEWFILES)"
697        fi
698        echo
699}
700
701
702
703#####################################################################
704####### Proceso de actualización de OpenGnSys
705#####################################################################
706
707
708echoAndLog "OpenGnSys update begins at $(date)"
709
710pushd $WORKDIR
711
712# Comprobar si hay conexión y detectar parámetros de red por defecto.
713checkNetworkConnection
714if [ $? -ne 0 ]; then
715        errorAndLog "Error connecting to server. Causes:"
716        errorAndLog " - Network is unreachable, review devices parameters."
717        errorAndLog " - You are inside a private network, configure the proxy service."
718        errorAndLog " - Server is temporally down, try agian later."
719        exit 1
720fi
721getNetworkSettings
722
723# Comprobar auto-actualización del programa.
724if [ "$PROGRAMDIR" != "$INSTALL_TARGET/bin" ]; then
725        checkAutoUpdate
726        if [ $? -ne 0 ]; then
727                echoAndLog "OpenGnSys updater has been overwritten."
728                echoAndLog "Please, re-execute this script."
729                exit
730        fi
731fi
732
733# Detectar datos de auto-configuración del instalador.
734autoConfigure
735
736# Instalar dependencias.
737installDependencies $DEPENDENCIES
738if [ $? -ne 0 ]; then
739        errorAndLog "Error: you may install all needed dependencies."
740        exit 1
741fi
742
743# Arbol de directorios de OpenGnSys.
744createDirs ${INSTALL_TARGET}
745if [ $? -ne 0 ]; then
746        errorAndLog "Error while creating directory paths!"
747        exit 1
748fi
749
750# Si es necesario, descarga el repositorio de código en directorio temporal
751if [ $USESVN -eq 1 ]; then
752        svnExportCode $SVN_URL
753        if [ $? -ne 0 ]; then
754                errorAndLog "Error while getting code from svn"
755                exit 1
756        fi
757else
758        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
759fi
760
761# Si existe fichero de actualización de la base de datos; aplicar cambios.
762INSTVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt)
763REPOVERSION=$(awk '{print $2}' $WORKDIR/opengnsys/doc/VERSION.txt)
764if [ "$INSTVERSION" == "$REPOVERSION" ]; then
765        OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION.sql"
766else
767        OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
768fi
769if [ -f $OPENGNSYS_DBUPDATEFILE ]; then
770        echoAndLog "Updating tables from file: $(basename $OPENGNSYS_DBUPDATEFILE)"
771        importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $OPENGNSYS_DBUPDATEFILE
772else
773        echoAndLog "Database unchanged."
774fi
775
776# Actualizar ficheros complementarios del servidor
777updateServerFiles
778if [ $? -ne 0 ]; then
779        errorAndLog "Error updating OpenGnSys Server files"
780        exit 1
781fi
782
783# Actualizar ficheros del cliente
784updateClientFiles
785updateInterfaceAdm
786
787# Actualizar páqinas web
788apacheConfiguration
789updateWebFiles
790if [ $? -ne 0 ]; then
791        errorAndLog "Error updating OpenGnSys Web Admin files"
792        exit 1
793fi
794# Generar páginas Doxygen para instalar en el web
795makeDoxygenFiles
796
797# Recompilar y actualizar los servicios del sistema
798compileServices
799
800# Actaulizar ficheros auxiliares del cliente
801updateClient
802if [ $? -ne 0 ]; then
803        errorAndLog "Error updating clients"
804        exit 1
805fi
806
807# Eliminamos el fichero de estado del tracker porque es incompatible entre los distintos paquetes
808if [ -f /tmp/dstate ]; then
809        rm -f /tmp/dstate
810fi
811
812# Mostrar resumen de actualización.
813updateSummary
814
815#rm -rf $WORKDIR
816echoAndLog "OpenGnSys update finished at $(date)"
817
818popd
819
Note: See TracBrowser for help on using the repository browser.