source: installer/opengnsys_update.sh @ 9c05bc7

Last change on this file since 9c05bc7 was 4181251, checked in by ramon <ramongomez@…>, 9 years ago

Versión 1.0.6a, #730: Integrar código y liberar la versión de mantenimiento OpenGnSys 1.0.6a.

git-svn-id: https://opengnsys.es/svn/trunk@4820 a21b9725-9963-47de-94b9-378ad31fedc9

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