source: installer/opengnsys_update.sh @ 96f39d0

Last change on this file since 96f39d0 was fac0b87, checked in by ramon <ramongomez@…>, 8 years ago

#754: Integrar los cambios de la versión de mantenimiento OpenGnSys 1.0.6b a la rama principal.

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

  • Property mode set to 100755
File size: 34.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        local ENGINECFG=$INSTALL_TARGET/client/etc/engine.cfg
404
405        # Actualizar ficheros del cliente.
406        backupFile $ENGINECFG
407        echoAndLog "${FUNCNAME}(): Updating OpenGnSys Client files."
408        rsync --exclude .svn -irplt $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
409        if [ $? -ne 0 ]; then
410                errorAndLog "${FUNCNAME}(): error while updating client structure"
411                exit 1
412        fi
413        find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null
414
415        # Actualizar librerías del motor de clonación.
416        echoAndLog "${FUNCNAME}(): Updating OpenGnSys Cloning Engine files."
417        rsync --exclude .svn -irplt $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
418        if [ $? -ne 0 ]; then
419                errorAndLog "${FUNCNAME}(): error while updating engine files"
420                exit 1
421        fi
422        if ! diff -q ${ENGINECFG}{,-LAST} &>/dev/null; then
423                NEWFILES="$NEWFILES $ENGINECFG"
424        else
425                rm -f ${ENGINECFG}-LAST
426        fi
427
428        echoAndLog "${FUNCNAME}(): client files update success."
429}
430
431# Configurar HTTPS y exportar usuario y grupo del servicio Apache.
432function apacheConfiguration ()
433{
434        # Activar HTTPS (solo actualizando desde versiones anteriores a 1.0.2).
435        if [ -e $APACHECFGDIR/sites-available/opengnsys.conf ]; then
436                echoAndLog "${FUNCNAME}(): Configuring HTTPS access..."
437                mv $APACHECFGDIR/sites-available/opengnsys.conf $APACHECFGDIR/sites-available/opengnsys
438                a2ensite default-ssl
439                a2enmod ssl
440                a2dissite opengnsys.conf
441                a2ensite opengnsys
442                $APACHESERV restart
443        fi
444
445        # Variables de ejecución de Apache.
446        # - APACHE_RUN_USER
447        # - APACHE_RUN_GROUP
448        if [ -f $APACHECFGDIR/envvars ]; then
449                source $APACHECFGDIR/envvars
450        fi
451        APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
452        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
453}
454
455# Configurar servicio Rsync.
456function rsyncConfigure()
457{
458        local service
459
460        # Configurar acceso a Rsync.
461        if [ ! -f /etc/rsyncd.conf ]; then
462                echoAndLog "${FUNCNAME}(): Configuring Rsync service."
463                NEWFILES="$NEWFILES /etc/rsyncd.conf"
464                sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENTUSER/g" \
465                    $WORKDIR/opengnsys/repoman/etc/rsyncd.conf.tmpl > /etc/rsyncd.conf
466                # Habilitar Rsync.
467                if [ -f /etc/default/rsync ]; then
468                        perl -pi -e 's/RSYNC_ENABLE=.*/RSYNC_ENABLE=inetd/' /etc/default/rsync
469                fi
470                if [ -f $INETDCFGDIR/rsync ]; then
471                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/rsync
472                else
473                        cat << EOT > $INETDCFGDIR/rsync
474service rsync
475{
476        disable = no
477        socket_type = stream
478        wait = no
479        user = root
480        server = $(which rsync)
481        server_args = --daemon
482        log_on_failure += USERID
483        flags = IPv6
484}
485EOT
486                fi
487                # Activar e iniciar Rsync.
488                service="rsync"  $ENABLESERVICE
489                service="xinetd"
490                $ENABLESERVICE; $STARTSERVICE
491        fi
492}
493
494# Copiar ficheros del OpenGnSys Web Console.
495function updateWebFiles()
496{
497        local ERRCODE COMPATDIR f
498
499        echoAndLog "${FUNCNAME}(): Updating web files..."
500
501        # Copiar los ficheros nuevos conservando el archivo de configuración de acceso.
502        backupFile $INSTALL_TARGET/www/controlacceso.php
503        mv $INSTALL_TARGET/www $INSTALL_TARGET/WebConsole
504        rsync --exclude .svn -irplt $WORKDIR/opengnsys/admin/WebConsole $INSTALL_TARGET
505        ERRCODE=$?
506        mv $INSTALL_TARGET/WebConsole $INSTALL_TARGET/www
507        unzip -o $WORKDIR/opengnsys/admin/xajax_0.5_standard.zip -d $INSTALL_TARGET/www/xajax
508        if [ $ERRCODE != 0 ]; then
509                errorAndLog "${FUNCNAME}(): Error updating web files."
510                exit 1
511        fi
512        restoreFile $INSTALL_TARGET/www/controlacceso.php
513
514        # Cambiar acceso a protocolo HTTPS.
515        if grep -q "http://" $INSTALL_TARGET/www/controlacceso.php 2>/dev/null; then
516                echoAndLog "${FUNCNAME}(): updating web access file"
517                perl -pi -e 's!http://!https://!g' $INSTALL_TARGET/www/controlacceso.php
518                NEWFILES="$NEWFILES $INSTALL_TARGET/www/controlacceso.php"
519        fi
520
521        # Compatibilidad con dispositivos móviles.
522        COMPATDIR="$INSTALL_TARGET/www/principal"
523        for f in acciones administracion aula aulas hardwares imagenes menus repositorios softwares; do
524                sed 's/clickcontextualnodo/clicksupnodo/g' $COMPATDIR/$f.php > $COMPATDIR/$f.device.php
525        done
526        cp -a $COMPATDIR/imagenes.device.php $COMPATDIR/imagenes.device4.php
527
528        # Cambiar permisos para ficheros especiales.
529        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/images/{fotos,iconos}
530        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/tmp/
531
532        echoAndLog "${FUNCNAME}(): Web files updated successfully."
533}
534
535# Copiar carpeta de Interface
536function updateInterfaceAdm()
537{
538        local errcode=0
539
540        # Crear carpeta y copiar Interface
541        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
542        mv $INSTALL_TARGET/client/interfaceAdm $INSTALL_TARGET/client/Interface
543        rsync --exclude .svn -irplt $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client
544        errcoce=$?
545        mv $INSTALL_TARGET/client/Interface $INSTALL_TARGET/client/interfaceAdm
546        if [ $errcode -ne 0 ]; then
547                echoAndLog "${FUNCNAME}(): error while updating admin interface"
548                exit 1
549        fi
550        chmod -R +x $INSTALL_TARGET/client/interfaceAdm
551        chown $OPENGNSYS_CLIENTUSER:$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
552        chmod 700 $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
553        echoAndLog "${FUNCNAME}(): Admin interface updated successfully."
554}
555
556# Crear documentación Doxygen para la consola web.
557function makeDoxygenFiles()
558{
559        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
560        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
561                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
562        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
563                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
564                return 1
565        fi
566        rm -fr "$INSTALL_TARGET/www/api"
567        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
568        rm -fr $INSTALL_TARGET/www/{man,perlmod,rtf}
569        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/api
570        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
571}
572
573
574# Crea la estructura base de la instalación de opengnsys
575function createDirs()
576{
577        # Crear estructura de directorios.
578        echoAndLog "${FUNCNAME}(): creating directory paths in ${INSTALL_TARGET}"
579        local dir
580
581        mkdir -p ${INSTALL_TARGET}/{bin,doc,etc,lib,sbin,www}
582        mkdir -p ${INSTALL_TARGET}/{client,images}
583        mkdir -p ${INSTALL_TARGET}/log/clients
584        ln -fs ${INSTALL_TARGET}/log /var/log/opengnsys
585        # Detectar directorio de instalación de TFTP.
586        if [ ! -L ${INSTALL_TARGET}/tftpboot ]; then
587                for dir in /var/lib/tftpboot /srv/tftp; do
588                        [ -d $dir ] && ln -fs $dir ${INSTALL_TARGET}/tftpboot
589                done
590        fi
591        mkdir -p ${INSTALL_TARGET}/tftpboot/menu.lst
592        if [ $? -ne 0 ]; then
593                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
594                return 1
595        fi
596
597        # Crear usuario ficticio.
598        if id -u $OPENGNSYS_CLIENTUSER &>/dev/null; then
599                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENTUSER\" is already created"
600        else
601                echoAndLog "${FUNCNAME}(): creating OpenGnSys user"
602                useradd $OPENGNSYS_CLIENTUSER 2>/dev/null
603                if [ $? -ne 0 ]; then
604                        errorAndLog "${FUNCNAME}(): error creating OpenGnSys user"
605                        return 1
606                fi
607        fi
608
609        # Establecer los permisos básicos.
610        echoAndLog "${FUNCNAME}(): setting directory permissions"
611        chmod -R 775 $INSTALL_TARGET/{log/clients,images,tftpboot/menu.lst}
612        mkdir -p $INSTALL_TARGET/tftpboot/menu.lst/examples
613        ! [ -f $INSTALL_TARGET/tftpboot/menu.lst/templates/00unknown ] && mv $INSTALL_TARGET/tftpboot/menu.lst/templates/* $INSTALL_TARGET/tftpboot/menu.lst/examples
614        chown -R :$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/{log/clients,images,tftpboot/menu.lst}
615        if [ $? -ne 0 ]; then
616                errorAndLog "${FUNCNAME}(): error while setting permissions"
617                return 1
618        fi
619
620        # Mover el fichero de registro al directorio de logs.
621        echoAndLog "${FUNCNAME}(): moving update log file"
622        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
623        chmod 600 $LOG_FILE
624
625        echoAndLog "${FUNCNAME}(): directory paths created"
626        return 0
627}
628
629# Copia ficheros de configuración y ejecutables genéricos del servidor.
630function updateServerFiles()
631{
632        # No copiar ficheros del antiguo cliente Initrd
633        local SOURCES=( repoman/bin \
634                        server/bin \
635                        admin/Sources/Services/ogAdmServerAux \
636                        admin/Sources/Services/ogAdmRepoAux \
637                        server/tftpboot \
638                        installer/opengnsys_uninstall.sh \
639                        doc )
640        local TARGETS=( bin \
641                        bin \
642                        sbin/ogAdmServerAux \
643                        sbin/ogAdmRepoAux \
644                        tftpboot \
645                        lib/opengnsys_uninstall.sh \
646                        doc )
647
648        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
649                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
650                exit 1
651        fi
652
653        echoAndLog "${FUNCNAME}(): updating files in server directories"
654        pushd $WORKDIR/opengnsys >/dev/null
655        local i
656        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
657                if [ -d "$INSTALL_TARGET/${TARGETS[i]}" ]; then
658                        rsync --exclude .svn -irplt "${SOURCES[i]}" $(dirname $(readlink -e "$INSTALL_TARGET/${TARGETS[i]}"))
659                else
660                        rsync -irplt "${SOURCES[i]}" $(readlink -m "$INSTALL_TARGET/${TARGETS[i]}")
661                fi
662        done
663        popd >/dev/null
664        NEWFILES=""             # Ficheros de configuración que han cambiado de formato.
665        if grep -q 'pxelinux.0' /etc/dhcp*/dhcpd*.conf; then
666                echoAndLog "${FUNCNAME}(): updating DHCP files"
667                perl -pi -e 's/pxelinux.0/grldr/' /etc/dhcp*/dhcpd*.conf
668                $DHCPSERV restart
669                NEWFILES="/etc/dhcp*/dhcpd*.conf"
670        fi
671        if ! diff -q $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys 2>/dev/null; then
672                echoAndLog "${FUNCNAME}(): updating new init file"
673                backupFile /etc/init.d/opengnsys
674                cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
675                NEWFILES="$NEWFILES /etc/init.d/opengnsys"
676        fi
677        if egrep -q "(UrlMsg=.*msgbrowser.php)|(UrlMenu=http://)" $INSTALL_TARGET/client/etc/ogAdmClient.cfg 2>/dev/null; then
678                echoAndLog "${FUNCNAME}(): updating new client config file"
679                backupFile $INSTALL_TARGET/client/etc/ogAdmClient.cfg
680                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
681                NEWFILES="$NEWFILES $INSTALL_TARGET/client/etc/ogAdmClient.cfg"
682        fi
683        echoAndLog "${FUNCNAME}(): updating cron files"
684        [ ! -f /etc/cron.d/opengnsys ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
685        [ ! -f /etc/cron.d/torrentcreator ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
686        [ ! -f /etc/cron.d/torrenttracker ] && echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
687        [ ! -f /etc/cron.d/imagedelete ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
688        echoAndLog "${FUNCNAME}(): server files updated successfully."
689}
690
691####################################################################
692### Funciones de compilación de código fuente de servicios
693####################################################################
694
695# Mueve el fichero del nuevo servicio si es distinto al del directorio destino.
696function moveNewService()
697{
698        local service
699
700        # Recibe 2 parámetros: fichero origen y directorio destino.
701        [ $# == 2 ] || return 1
702        [ -f  $1 -a -d $2 ] || return 1
703
704        # Comparar los ficheros.
705        if ! diff -q $1 $2/$(basename $1) &>/dev/null; then
706                # Parar los servicios si fuese necesario.
707                [ -z "$NEWSERVICES" ] && service="opengnsys" $STOPSERVICE
708                # Nuevo servicio.
709                NEWSERVICES="$NEWSERVICES $(basename $1)"
710                # Mover el nuevo fichero de servicio
711                mv $1 $2
712        fi
713}
714
715
716# Recompilar y actualiza los serivicios y clientes.
717function compileServices()
718{
719        local hayErrores=0
720
721        # Compilar OpenGnSys Server
722        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Admin Server"
723        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
724        make && moveNewService ogAdmServer $INSTALL_TARGET/sbin
725        if [ $? -ne 0 ]; then
726                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Admin Server"
727                hayErrores=1
728        fi
729        popd
730        # Compilar OpenGnSys Repository Manager
731        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Repository Manager"
732        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo
733        make && moveNewService ogAdmRepo $INSTALL_TARGET/sbin
734        if [ $? -ne 0 ]; then
735                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Repository Manager"
736                hayErrores=1
737        fi
738        popd
739        # Compilar OpenGnSys Agent
740        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Agent"
741        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
742        make && moveNewService ogAdmAgent $INSTALL_TARGET/sbin
743        if [ $? -ne 0 ]; then
744                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Agent"
745                hayErrores=1
746        fi
747        popd
748
749        # Compilar OpenGnSys Client
750        echoAndLog "${FUNCNAME}(): Recompiling OpenGnSys Client"
751        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
752        make && mv ogAdmClient $INSTALL_TARGET/client/bin
753        if [ $? -ne 0 ]; then
754                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Client"
755                hayErrores=1
756        fi
757        popd
758
759        return $hayErrores
760}
761
762
763####################################################################
764### Funciones instalacion cliente OpenGnSys
765####################################################################
766
767# Actualizar cliente OpenGnSys
768function updateClient()
769{
770        local DOWNLOADURL="http://$OPENGNSYS_SERVER/downloads"
771        local FILENAME=ogLive-precise-3.2.0-23-generic-r4311.iso        # 1.0.4-rc4
772        #local FILENAME=ogLive-precise-3.11.0-26-generic-r4413.iso      # 1.0.6-rc1
773        local SOURCEFILE=$DOWNLOADURL/$FILENAME
774        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
775        local SOURCELENGTH TARGETLENGTH
776        local TMPDIR=/tmp/${FILENAME%.iso}
777        local OGINITRD=$INSTALL_TARGET/tftpboot/ogclient/oginitrd.img
778        local OGVMLINUZ=$INSTALL_TARGET/tftpboot/ogclient/ogvmlinuz
779        local SAMBAPASS
780        local KERNELVERSION
781        local RSYNCSERV RSYNCCLNT
782
783        # Comprobar si debe actualizarse el cliente.
784        SOURCELENGTH=$(LANG=C wget --spider $SOURCEFILE 2>&1 | awk '/Length:/ {print $2}')
785        TARGETLENGTH=$(ls -l $TARGETFILE 2>/dev/null | awk '{print $5}')
786        [ -z $TARGETLENGTH ] && TARGETLENGTH=0
787        if [ "$SOURCELENGTH" != "$TARGETLENGTH" ]; then
788                echoAndLog "${FUNCNAME}(): Loading Client"
789                wget $DOWNLOADURL/$FILENAME -O $TARGETFILE
790                if [ ! -s $TARGETFILE ]; then
791                        errorAndLog "${FUNCNAME}(): Error loading OpenGnSys Client"
792                        return 1
793                fi
794                # Obtener la clave actual de acceso a Samba para restaurarla.
795                if [ -f $OGINITRD ]; then
796                        SAMBAPASS=$(gzip -dc $OGINITRD | \
797                                    cpio -i --to-stdout scripts/ogfunctions 2>&1 | \
798                                    grep "^[    ].*OPTIONS=" | \
799                                    sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
800                fi
801                # Montar la imagen ISO del ogclient, actualizar ficheros y desmontar.
802                echoAndLog "${FUNCNAME}(): Updatting ogclient files"
803                mkdir -p $TMPDIR
804                mount -o loop,ro $TARGETFILE $TMPDIR
805                rsync -irlt $TMPDIR/ogclient $INSTALL_TARGET/tftpboot
806                umount $TMPDIR
807                rmdir $TMPDIR
808                # Recuperar la clave de acceso a Samba.
809                if [ -n "$SAMBAPASS" ]; then
810                        echoAndLog "${FUNCNAME}(): Restoring client access key"
811                        echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | \
812                                        $INSTALL_TARGET/bin/setsmbpass
813                fi
814                # Establecer los permisos.
815                find -L $INSTALL_TARGET/tftpboot -type d -exec chmod 755 {} \;
816                find -L $INSTALL_TARGET/tftpboot -type f -exec chmod 644 {} \;
817                chown -R :$OPENGNSYS_CLIENTUSER $INSTALL_TARGET/tftpboot/ogclient
818                chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/tftpboot/menu.lst
819               
820                # Ofrecer md5 del kernel y vmlinuz para ogupdateinitrd en cache
821                cp -av $INSTALL_TARGET/tftpboot/ogclient/ogvmlinuz* $INSTALL_TARGET/tftpboot
822                cp -av $INSTALL_TARGET/tftpboot/ogclient/oginitrd.img* $INSTALL_TARGET/tftpboot
823               
824                # Obtiene versión del Kernel del cliente (con 2 decimales).
825                KERNELVERSION=$(file -bkr $OGVMLINUZ 2>/dev/null | \
826                                awk '/Linux/ { for (i=1; i<=NF; i++)
827                                                   if ($i~/version/) {
828                                                      v=$(i+1);
829                                                      printf ("%d",v);
830                                                      sub (/[0-9]*\./,"",v);
831                                                      printf (".%02d",v)
832                                             } }')
833                # Actaulizar la base de datos adaptada al Kernel del cliente.
834                OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-postinst.sql"
835                if [ -f $OPENGNSYS_DBUPDATEFILE ]; then
836                        perl -pi -e "s/KERNELVERSION/$KERNELVERSION/g" $OPENGNSYS_DBUPDATEFILE
837                        importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $OPENGNSYS_DBUPDATEFILE
838                fi
839
840                # Montar SquashFS para comprobar versión de Rsync.
841                mkdir -p $TMPDIR
842                mount -o loop,ro $INSTALL_TARGET/tftpboot/ogclient/ogclient.sqfs $TMPDIR
843                # Si versión Rsync de servidor > cliente, enlazar a fichero compilado.
844                RSYNCSERV=$(rsync --version 2>/dev/null | awk '/protocol/ {print $6}')
845                RSYNCCLNT=$(chroot $TMPDIR /usr/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}')
846                if [ -z "$RSYNCSERV" -o ${RSYNCSERV:-0} -gt ${RSYNCCLNT:-1} ]; then
847                        [ -e $INSTALL_TARGET/client/bin/rsync-$RSYNCSERV ] && mv -f $INSTALL_TARGET/client/bin/rsync-$RSYNCSERV $INSTALL_TARGET/client/bin/rsync
848                else
849                        # Si no, renombrar fichero compilado con nº de protocolo.
850                        [ -e $INSTALL_TARGET/client/bin/rsync ] && mv -f $INSTALL_TARGET/client/bin/rsync $INSTALL_TARGET/client/bin/rsync-$($INSTALL_TARGET/client/bin/rsync --version 2>/dev/null | awk '/protocol/ {print $6}')
851                fi
852                # Desmontar SquashFS.
853                umount $TMPDIR
854                rmdir $TMPDIR
855                CLIENTUPDATED=${FILENAME%.*}
856
857                echoAndLog "${FUNCNAME}(): Client update successfully"
858        else
859                # Si no existe, crear el fichero de claves de Rsync.
860                if [ ! -f /etc/rsyncd.secrets ]; then
861                        echoAndLog "${FUNCNAME}(): Restoring client access key"
862                        SAMBAPASS=$(gzip -dc $OGINITRD | \
863                                    cpio -i --to-stdout scripts/ogfunctions 2>&1 | \
864                                    grep "^[    ].*OPTIONS=" | \
865                                    sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
866                        echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | \
867                                        $INSTALL_TARGET/bin/setsmbpass
868                else
869                        echoAndLog "${FUNCNAME}(): Client is already updated"
870                fi
871        fi
872        # Versión del ogLive instalado
873        echo "${FILENAME%.*}" > $INSTALL_TARGET/doc/veroglive.txt
874}
875
876# Comprobar permisos y ficheros.
877function checkFiles()
878{
879        # Comprobar permisos adecuados.
880        if [ -x $INSTALL_TARGET/bin/checkperms ]; then
881                echoAndLog "${FUNCNAME}(): Checking permissions."
882                OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENTUSER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" $INSTALL_TARGET/bin/checkperms
883        fi
884
885        # Eliminamos el fichero de estado del tracker porque es incompatible entre los distintos paquetes
886        if [ -f /tmp/dstate ]; then
887                echoAndLog "${FUNCNAME}(): Delete unused files."
888                rm -f /tmp/dstate
889        fi
890}
891
892# Resumen de actualización.
893function updateSummary()
894{
895        # Actualizar fichero de versión y revisión.
896        local VERSIONFILE="$INSTALL_TARGET/doc/VERSION.txt"
897        local REVISION=$(LANG=C svn info $SVN_URL|awk '/Rev:/ {print "r"$4}')
898
899        [ -f $VERSIONFILE ] || echo "OpenGnSys" >$VERSIONFILE
900        perl -pi -e "s/($| r[0-9]*)/ $REVISION/" $VERSIONFILE
901
902        echo
903        echoAndLog "OpenGnSys Update Summary"
904        echo       "========================"
905        echoAndLog "Project version:                  $(cat $VERSIONFILE)"
906        echoAndLog "Update log file:                  $LOG_FILE"
907        if [ -n "$NEWFILES" ]; then
908                echoAndLog "Check new config files:           $(echo $NEWFILES)"
909        fi
910        if [ -n "$NEWSERVICES" ]; then
911                echoAndLog "New compiled services:            $(echo $NEWSERVICES)"
912                # Indicar si se debe reiniciar servicios manualmente o usando el Cron.
913                [ -f /etc/default/opengnsys ] && source /etc/default/opengnsys
914                if [ "$RUN_CRONJOB" == "no" ]; then
915                        echoAndLog "        WARNING: you must restart OpenGnSys services manually."
916                else
917                        echoAndLog "        New OpenGnSys services will be restarted by the cronjob."
918                fi
919        fi
920        echoAndLog "Warnings:"
921        echoAndLog " - You must to clear web browser cache before loading OpenGnSys page."
922        if [ -n "$CLIENTUPDATED" ]; then
923                echoAndLog " - ogLive Client is updated to: $CLIENTUPDATED"
924        fi
925        echoAndLog " - Launch $INSTALL_TARGET/bin/installoglive script and select new ogLive"
926        echoAndLog "      for clients' hardware compatibilty."
927        echo
928}
929
930
931
932#####################################################################
933####### Proceso de actualización de OpenGnSys
934#####################################################################
935
936
937echoAndLog "OpenGnSys update begins at $(date)"
938
939pushd $WORKDIR
940
941# Comprobar si hay conexión y detectar parámetros de red por defecto.
942checkNetworkConnection
943if [ $? -ne 0 ]; then
944        errorAndLog "Error connecting to server. Causes:"
945        errorAndLog " - Network is unreachable, review devices parameters."
946        errorAndLog " - You are inside a private network, configure the proxy service."
947        errorAndLog " - Server is temporally down, try agian later."
948        exit 1
949fi
950getNetworkSettings
951
952# Comprobar auto-actualización del programa.
953if [ "$PROGRAMDIR" != "$INSTALL_TARGET/bin" ]; then
954        checkAutoUpdate
955        if [ $? -ne 0 ]; then
956                echoAndLog "OpenGnSys updater has been overwritten."
957                echoAndLog "Please, re-execute this script."
958                exit
959        fi
960fi
961
962# Detectar datos de auto-configuración del instalador.
963autoConfigure
964
965# Instalar dependencias.
966installDependencies ${DEPENDENCIES[*]}
967if [ $? -ne 0 ]; then
968        errorAndLog "Error: you may install all needed dependencies."
969        exit 1
970fi
971
972# Arbol de directorios de OpenGnSys.
973createDirs ${INSTALL_TARGET}
974if [ $? -ne 0 ]; then
975        errorAndLog "Error while creating directory paths!"
976        exit 1
977fi
978
979# Si es necesario, descarga el repositorio de código en directorio temporal
980if [ $USESVN -eq 1 ]; then
981        svnExportCode $SVN_URL
982        if [ $? -ne 0 ]; then
983                errorAndLog "Error while getting code from svn"
984                exit 1
985        fi
986else
987        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
988fi
989
990# Si existe fichero de actualización de la base de datos; aplicar cambios.
991INSTVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt)
992REPOVERSION=$(awk '{print $2}' $WORKDIR/opengnsys/doc/VERSION.txt)
993if [ "$INSTVERSION" == "$REPOVERSION" ]; then
994        OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION.sql"
995else
996        OPENGNSYS_DBUPDATEFILE="$WORKDIR/opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
997fi
998if [ -f $OPENGNSYS_DBUPDATEFILE ]; then
999        echoAndLog "Updating tables from file: $(basename $OPENGNSYS_DBUPDATEFILE)"
1000        importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $OPENGNSYS_DBUPDATEFILE
1001else
1002        echoAndLog "Database unchanged."
1003fi
1004
1005# Actualizar ficheros complementarios del servidor
1006updateServerFiles
1007if [ $? -ne 0 ]; then
1008        errorAndLog "Error updating OpenGnSys Server files"
1009        exit 1
1010fi
1011
1012# Configurar Rsync.
1013rsyncConfigure
1014
1015# Actualizar ficheros del cliente
1016updateClientFiles
1017updateInterfaceAdm
1018
1019# Actualizar páqinas web
1020apacheConfiguration
1021updateWebFiles
1022if [ $? -ne 0 ]; then
1023        errorAndLog "Error updating OpenGnSys Web Admin files"
1024        exit 1
1025fi
1026# Generar páginas Doxygen para instalar en el web
1027makeDoxygenFiles
1028
1029# Recompilar y actualizar los servicios del sistema
1030compileServices
1031
1032# Actaulizar ficheros auxiliares del cliente
1033updateClient
1034if [ $? -ne 0 ]; then
1035        errorAndLog "Error updating clients"
1036        exit 1
1037fi
1038
1039# Comprobar permisos y ficheros.
1040checkFiles
1041
1042# Mostrar resumen de actualización.
1043updateSummary
1044
1045#rm -rf $WORKDIR
1046echoAndLog "OpenGnSys update finished at $(date)"
1047
1048popd
1049
Note: See TracBrowser for help on using the repository browser.