source: installer/opengnsys_update.sh @ 9dba4c18

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 9dba4c18 was 42a0e41, checked in by ramon <ramongomez@…>, 12 years ago

#493: Instalador y actualizador copian servicio auxiliar ogAdmServerAux; separar los logs de ambos scripts.

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

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