source: installer/opengnsys_update.sh @ f256817

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

#673: Cambiar mensaje de error por mensaje de aviso cuando el actualizador no puede crear copia de seguridad de un fichero.

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

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