source: installer/opengnsys_update.sh @ a37e5fc4

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

#804: Instalar y actualizar a PHP 7.

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

  • Property mode set to 100755
File size: 37.4 KB
RevLine 
[a0867b37]1#!/bin/bash
2#/**
3#@file    opengnsys_update.sh
[5f21d34]4#@brief   Script actualización de OpenGnsys
[a0867b37]5#@version 0.9 - basado en opengnsys_installer.sh
6#@author  Ramón Gómez - ETSII Univ. Sevilla
7#@date    2010/01/27
[c1e00e4]8#@version 1.0 - adaptación a OpenGnSys 1.0
9#@author  Ramón Gómez - ETSII Univ. Sevilla
10#@date    2011/03/02
[64dd765]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
[739fb00]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
[1175096]17#@version 1.0.3 - Compatibilidad con Debian y auto configuración de acceso a BD.
[7bb72f7]18#@author  Ramón Gómez - ETSII Univ. Sevilla
[1175096]19#@date    2012/03/12
[db9e706]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
[dde65c7]23#@version 1.0.5 - Actualizar BD en la misma versión, compatibilidad con Fedora (systemd) y configuración de Rsync.
[0b8a1f1]24#@author  Ramón Gómez - ETSII Univ. Sevilla
[dde65c7]25#@date    2014/04/03
[1a2fa9d8]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
[a3855dc]29#@version 1.1.0 - Instalación de API REST y configuración de zona horaria.
[900be258]30#@author  Ramón Gómez - ETSII Univ. Sevilla
[a3855dc]31#@date    2015/11/09
[a0867b37]32#*/
33
34
[1175096]35####  AVISO: NO EDITAR variables de configuración.
36####  WARNING: DO NOT EDIT configuration variables.
37INSTALL_TARGET=/opt/opengnsys           # Directorio de instalación
[ec045b1]38PATH=$PATH:$INSTALL_TARGET/bin
[295b4ab]39OPENGNSYS_CLIENTUSER="opengnsys"        # Usuario Samba
40
41
[a0867b37]42# Sólo ejecutable por usuario root
[6ef01d9]43if [ "$(whoami)" != 'root' ]; then
[a0867b37]44        echo "ERROR: this program must run under root privileges!!"
45        exit 1
46fi
[5f21d34]47# Error si OpenGnsys no está instalado (no existe el directorio del proyecto)
[4e51cb0]48if [ ! -d $INSTALL_TARGET ]; then
[5f21d34]49        echo "ERROR: OpenGnsys is not installed, cannot update!!"
[4e51cb0]50        exit 1
51fi
[1175096]52# Cargar configuración de acceso a la base de datos.
53if [ -r $INSTALL_TARGET/etc/ogAdmServer.cfg ]; then
54        source $INSTALL_TARGET/etc/ogAdmServer.cfg
55elif [ -r $INSTALL_TARGET/etc/ogAdmAgent.cfg ]; then
56        source $INSTALL_TARGET/etc/ogAdmAgent.cfg
57fi
[42a0e41]58OPENGNSYS_DATABASE=${OPENGNSYS_DATABASE:-"$CATALOG"}            # Base de datos
[1175096]59OPENGNSYS_DBUSER=${OPENGNSYS_DBUSER:-"$USUARIO"}                # Usuario de acceso
60OPENGNSYS_DBPASSWORD=${OPENGNSYS_DBPASSWORD:-"$PASSWORD"}       # Clave del usuario
61if [ -z "$OPENGNSYS_DATABASE" -o -z "$OPENGNSYS_DBUSER" -o -z "$OPENGNSYS_DBPASSWORD" ]; then
62        echo "ERROR: set OPENGNSYS_DATABASE, OPENGNSYS_DBUSER and OPENGNSYS_DBPASSWORD"
63        echo "       variables, and run this script again."
[0304465]64        exit 1
[1175096]65fi
[a0867b37]66
67# Comprobar si se ha descargado el paquete comprimido (USESVN=0) o sólo el instalador (USESVN=1).
68PROGRAMDIR=$(readlink -e $(dirname "$0"))
[64dd765]69PROGRAMNAME=$(basename "$0")
[a0081b7]70OPENGNSYS_SERVER="opengnsys.es"
[a0867b37]71if [ -d "$PROGRAMDIR/../installer" ]; then
[6ef01d9]72        USESVN=0
[a0867b37]73else
[6ef01d9]74        USESVN=1
[a0867b37]75fi
[a0081b7]76SVN_URL="https://$OPENGNSYS_SERVER/svn/branches/version1.1/"
[a0867b37]77
78WORKDIR=/tmp/opengnsys_update
79mkdir -p $WORKDIR
80
[42a0e41]81# Registro de incidencias.
82OGLOGFILE=$INSTALL_TARGET/log/${PROGRAMNAME%.sh}.log
[57f7e9c]83LOG_FILE=/tmp/$(basename $OGLOGFILE)
[a0867b37]84
85
86
87#####################################################################
88####### Algunas funciones útiles de propósito general:
89#####################################################################
[295b4ab]90
[db9e706]91# Generar variables de configuración del actualizador
92# Variables globales:
[2e38f60]93# - OSDISTRIB - distribución Linux
[db9e706]94# - DEPENDENCIES - array de dependencias que deben estar instaladas
95# - UPDATEPKGLIST, INSTALLPKGS, CHECKPKG - comandos para gestión de paquetes
[65baf16]96# - APACHECFGDIR, APACHESERV, DHCPSERV, INETDCFGDIR - configuración y servicios
[db9e706]97function autoConfigure()
98{
[a37e5fc4]99        local service
[2e38f60]100
[a37e5fc4]101        # Detectar sistema operativo del servidor (compatible con fichero os-release y con LSB).
102        if [ -f /etc/os-release ]; then
103                source /etc/os-release
104                OSDISTRIB="$ID"
105                OSVERSION="$VERSION_ID"
106        else
107                OSDISTRIB=$(lsb_release -is 2>/dev/null)
108                OSVERSION=$(lsb_release -rs 2>/dev/null)
109        fi
110        # Convertir distribución a minúsculas y obtener solo el 1er número de versión.
111        OSDISTRIB="${OSDISTRIB,,}"
112        OSVERSION="${OSVERSION%%.*}"
113
114        # Configuración según la distribución de Linux.
115        if [ -f /etc/debian_version ]; then
116                # Distribución basada en paquetes Deb.
117                DEPENDENCIES=( curl rsync btrfs-tools procps arp-scan realpath php-curl gettext moreutils jq wakeonlan )
[0304465]118                UPDATEPKGLIST="add-apt-repository -y ppa:ondrej/php; apt-get update"
[a37e5fc4]119                INSTALLPKGS="apt-get -y install"
120                DELETEPKGS="apt-get -y purge"
[db9e706]121                CHECKPKG="dpkg -s \$package 2>/dev/null | grep -q \"Status: install ok\""
[4b96166]122                if which service &>/dev/null; then
123                        STARTSERVICE="eval service \$service restart"
[dde65c7]124                        STOPSERVICE="eval service \$service stop"
[a37e5fc4]125                        SERVICESTATUS="eval service \$service status"
[4b96166]126                else
127                        STARTSERVICE="eval /etc/init.d/\$service restart"
[dde65c7]128                        STOPSERVICE="eval /etc/init.d/\$service stop"
[a37e5fc4]129                        SERVICESTATUS="eval /etc/init.d/\$service status"
[4b96166]130                fi
131                ENABLESERVICE="eval update-rc.d \$service defaults"
[2e38f60]132                APACHEUSER="www-data"
133                APACHEGROUP="www-data"
[65baf16]134                INETDCFGDIR=/etc/xinetd.d
[a37e5fc4]135        elif [ -f /etc/redhat-release ]; then
136                # Distribución basada en paquetes rpm.
137                DEPENDENCIES=( curl rsync btrfs-progs procps-ng arp-scan gettext moreutils jq net-tools )
[2c8b9ed]138                # En CentOS 7 instalar arp-scan de CentOS 6.
139                [ "$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} )
[db9e706]140                INSTALLPKGS="yum install -y"
[a37e5fc4]141                DELETEPKGS="yum remove -y"
[db9e706]142                CHECKPKG="rpm -q --quiet \$package"
[4b96166]143                if which systemctl &>/dev/null; then
[a37e5fc4]144                        STARTSERVICE="eval systemctl restart \$service.service"
[dde65c7]145                        STOPSERVICE="eval systemctl stop \$service.service"
[4b96166]146                        ENABLESERVICE="eval systemctl enable \$service.service"
[a37e5fc4]147                        SERVICESTATUS="eval systemctl status \$service.service"
[4b96166]148                else
[a37e5fc4]149                        STARTSERVICE="eval service \$service restart"
[dde65c7]150                        STOPSERVICE="eval service \$service stop"
[4b96166]151                        ENABLESERVICE="eval chkconfig \$service on"
[a37e5fc4]152                        SERVICESTATUS="eval service \$service status"
[4b96166]153                fi
[2a5c1a4]154                APACHEUSER="apache"
155                APACHEGROUP="apache"
[65baf16]156                INETDCFGDIR=/etc/xinetd.d
[a37e5fc4]157        else
158                # Otras distribuciones.
159                :
160        fi
161        for service in apache2 httpd; do
162                [ -d /etc/$service ] && APACHECFGDIR="/etc/$service"
163                if $SERVICESTATUS &>/dev/null; then APACHESERV="$service"; fi
164        done
165        for service in dhcpd dhcpd3-server isc-dhcp-server; do
166                if $SERVICESTATUS &>/dev/null; then DHCPSERV="$service"; fi
167        done
[db9e706]168}
169
170
[64dd765]171# Comprobar auto-actualización.
172function checkAutoUpdate()
173{
174        local update=0
175
176        # Actaulizar el script si ha cambiado o no existe el original.
177        if [ $USESVN -eq 1 ]; then
[7b0c6ff]178                svn export $SVN_URL/installer/$PROGRAMNAME
[d372e6e]179                if ! diff -q $PROGRAMNAME $INSTALL_TARGET/lib/$PROGRAMNAME 2>/dev/null || ! test -f $INSTALL_TARGET/lib/$PROGRAMNAME; then
[64dd765]180                        mv $PROGRAMNAME $INSTALL_TARGET/lib
181                        update=1
182                else
183                        rm -f $PROGRAMNAME
184                fi
185        else
[d372e6e]186                if ! diff -q $PROGRAMDIR/$PROGRAMNAME $INSTALL_TARGET/lib/$PROGRAMNAME 2>/dev/null || ! test -f $INSTALL_TARGET/lib/$PROGRAMNAME; then
[64dd765]187                        cp -a $PROGRAMDIR/$PROGRAMNAME $INSTALL_TARGET/lib
188                        update=1
189                fi
190        fi
191
192        return $update
193}
194
195
[a0867b37]196function getDateTime()
197{
[5eb61a6]198        date "+%Y%m%d-%H%M%S"
[a0867b37]199}
200
201# Escribe a fichero y muestra por pantalla
202function echoAndLog()
203{
[5eb61a6]204        echo $1
[6ef01d9]205        DATETIME=`getDateTime`
206        echo "$DATETIME;$SSH_CLIENT;$1" >> $LOG_FILE
[a0867b37]207}
208
209function errorAndLog()
210{
[5eb61a6]211        echo "ERROR: $1"
212        DATETIME=`getDateTime`
[6ef01d9]213        echo "$DATETIME;$SSH_CLIENT;ERROR: $1" >> $LOG_FILE
[a0867b37]214}
215
[cd86637]216# Escribe a fichero y muestra mensaje de aviso
217function warningAndLog()
218{
219        local DATETIME=`getDateTime`
220        echo "Warning: $1"
221        echo "$DATETIME;$SSH_CLIENT;Warning: $1" >> $LOG_FILE
222}
223
[a0867b37]224
225#####################################################################
226####### Funciones de copia de seguridad y restauración de ficheros
227#####################################################################
228
229# Hace un backup del fichero pasado por parámetro
230# deja un -last y uno para el día
231function backupFile()
232{
233        if [ $# -ne 1 ]; then
234                errorAndLog "${FUNCNAME}(): invalid number of parameters"
235                exit 1
236        fi
237
238        local fichero=$1
239        local fecha=`date +%Y%m%d`
240
241        if [ ! -f $fichero ]; then
[cd86637]242                warningAndLog "${FUNCNAME}(): file $fichero doesn't exists"
[a0867b37]243                return 1
244        fi
245
[ebbbfc01]246        echoAndLog "${FUNCNAME}(): Making $fichero back-up"
[a0867b37]247
248        # realiza una copia de la última configuración como last
[6ef01d9]249        cp -a $fichero "${fichero}-LAST"
[a0867b37]250
251        # si para el día no hay backup lo hace, sino no
252        if [ ! -f "${fichero}-${fecha}" ]; then
[6ef01d9]253                cp -a $fichero "${fichero}-${fecha}"
[a0867b37]254        fi
255}
256
257# Restaura un fichero desde su copia de seguridad
258function restoreFile()
259{
260        if [ $# -ne 1 ]; then
261                errorAndLog "${FUNCNAME}(): invalid number of parameters"
262                exit 1
263        fi
264
265        local fichero=$1
266
[ebbbfc01]267        echoAndLog "${FUNCNAME}(): restoring file $fichero"
[a0867b37]268        if [ -f "${fichero}-LAST" ]; then
[6ef01d9]269                cp -a "$fichero-LAST" "$fichero"
[a0867b37]270        fi
271}
272
273
274#####################################################################
[295b4ab]275####### Funciones de acceso a base de datos
276#####################################################################
277
278# Actualizar la base datos
279function importSqlFile()
280{
281        if [ $# -ne 4 ]; then
282                errorAndLog "${FNCNAME}(): invalid number of parameters"
283                exit 1
284        fi
285
286        local dbuser="$1"
287        local dbpassword="$2"
288        local database="$3"
289        local sqlfile="$4"
290        local tmpfile=$(mktemp)
[632bd45]291        local mycnf=/tmp/.my.cnf.$$
[295b4ab]292        local status
[e00bb53]293        local APIKEY=$(php -r 'echo md5(uniqid(rand(), true));')
[f9b5714]294        REPOKEY=$(php -r 'echo md5(uniqid(rand(), true));')
[295b4ab]295
296        if [ ! -r $sqlfile ]; then
297                errorAndLog "${FUNCNAME}(): Unable to read $sqlfile!!"
298                return 1
299        fi
300
301        echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..."
302        chmod 600 $tmpfile
303        sed -e "s/SERVERIP/$SERVERIP/g" -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
[e00bb53]304            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
[8e0f770]305            -e "s/APIKEY/$APIKEY/g" -e "s/REPOKEY/$REPOKEY/g" $sqlfile > $tmpfile
[632bd45]306        # Componer fichero con credenciales de conexión. 
307        touch $mycnf
308        chmod 600 $mycnf
309        cat << EOT > $mycnf
[c073224]310[client]
[09bf701]311user=$dbuser
312password=$dbpassword
[632bd45]313EOT
314        # Ejecutar actualización y borrar fichero de credenciales.
[09bf701]315        mysql --defaults-extra-file=$mycnf --default-character-set=utf8 -D "$database" < $tmpfile
[295b4ab]316        status=$?
[632bd45]317        rm -f $mycnf $tmpfile
[295b4ab]318        if [ $status -ne 0 ]; then
319                errorAndLog "${FUNCNAME}(): error importing $sqlfile in database $database"
320                return 1
321        fi
322        echoAndLog "${FUNCNAME}(): file imported to database $database"
323        return 0
324}
325
[21372e8]326# Comprobar configuración de MySQL y recomendar cambios necesarios.
327function checkMysqlConfig()
328{
329        if [ $# -ne 2 ]; then
330                errorAndLog "${FNCNAME}(): invalid number of parameters"
331                exit 1
332        fi
333
334        local dbuser="$1"
335        local dbpassword="$2"
336        local mycnf=/tmp/.my.cnf.$$
337
[0304465]338        echoAndLog "${FUNCNAME}(): checking MySQL configuration"
[21372e8]339        touch $mycnf
340        cat << EOT > $mycnf
341[client]
342user=$dbuser
343password=$dbpassword
344EOT
345        # Check if scheduler is active.
346        if [ "$(mysql --defaults-extra-file=$mycnf -Nse 'SELECT @@GLOBAL.event_scheduler;')" = "OFF" ]; then
347                MYSQLCONFIG="SET GLOBAL event_scheduler = ON; "
348        fi
349        rm -f $mycnf
350
351        echoAndLog "${FUNCNAME}(): MySQL configuration has checked"
352        return 0
353}
[295b4ab]354
355#####################################################################
[a0867b37]356####### Funciones de instalación de paquetes
357#####################################################################
358
359# Instalar las deependencias necesarias para el actualizador.
[64dd765]360function installDependencies()
[a0867b37]361{
[db9e706]362        local package
363
[a37e5fc4]364        # Comprobar si hay que actualizar PHP 5 a PHP 7.
365        eval $UPDATEPKGLIST
366        if [ -f /etc/debian_version ]; then
367                # Basado en paquetes Deb.
368                PHP7VERSION=$(apt-cache pkgnames php7 2>/dev/null | sort | head -1)
369                PHP5PKGS=( $(dpkg -l |awk '$2~/^php5/ {print $2}') )
370                if [ -n "$PHP5PKGS" ]; then
371                        $DELETEPKGS ${PHP5PKGS[@]}
372                        PHP5PKGS[0]=$PHP7VERSION
373                        INSTALLDEPS=${PHP5PKGS[@]//php5*-/${PHP7VERSION}-}
374                fi
375        fi
376
[a0867b37]377        if [ $# = 0 ]; then
[0304465]378                echoAndLog "${FUNCNAME}(): no dependencies are needed"
[c1e00e4]379        else
380                while [ $# -gt 0 ]; do
[a37e5fc4]381                        package="${1/php/$PHP7VERSION}"
[b6fd406]382                        eval $CHECKPKG || INSTALLDEPS="$INSTALLDEPS $package"
[c1e00e4]383                        shift
384                done
385                if [ -n "$INSTALLDEPS" ]; then
[db9e706]386                        $INSTALLPKGS $INSTALLDEPS
[c1e00e4]387                        if [ $? -ne 0 ]; then
[0304465]388                                errorAndLog "${FUNCNAME}(): cannot install some dependencies: $INSTALLDEPS"
[c1e00e4]389                                return 1
390                        fi
391                fi
392        fi
[a0867b37]393}
394
395
396#####################################################################
397####### Funciones para el manejo de Subversion
398#####################################################################
399
400function svnExportCode()
401{
402        if [ $# -ne 1 ]; then
403                errorAndLog "${FUNCNAME}(): invalid number of parameters"
404                exit 1
405        fi
406
[27dc5ff]407        local url="$1"
[a0867b37]408
409        echoAndLog "${FUNCNAME}(): downloading subversion code..."
410
[7ad4465]411        svn checkout "${url}" opengnsys
[a0867b37]412        if [ $? -ne 0 ]; then
413                errorAndLog "${FUNCNAME}(): error getting code from ${url}, verify your user and password"
414                return 1
415        fi
416        echoAndLog "${FUNCNAME}(): subversion code downloaded"
417        return 0
418}
419
420
421############################################################
422###  Detectar red
423############################################################
424
[07c3a59]425# Comprobar si existe conexión.
426function checkNetworkConnection()
427{
[a0081b7]428        OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"opengnsys.es"}
[07c3a59]429        wget --spider -q $OPENGNSYS_SERVER
430}
431
[0304465]432# Comprobar si la versión es anterior a la actual.
433function checkVersion()
434{
435        local PRE
436
437        # Obtener versión actual y versión a actualizar.
438        OLDVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt 2>/dev/null)
439        if [ $USESVN -eq 1 ]; then
440                NEWVERSION=$(curl -s $SVN_URL/doc/VERSION.txt 2>/dev/null | awk '{print $2}')
441        else
442                NEWVERSION=$(awk '{print $2}' $PROGRAMDIR/doc/VERSION.txt 2>/dev/null)
443        fi
444        [[ "$NEWVERSION" =~ pre ]] && PRE=1
445
446        # Comparar versiones.
447        [[ "$NEWVERSION" < "${OLDVERSION/pre/}" ]] && return 1
448        [ "${NEWVERSION/pre/}" == "$OLDVERSION" -a "$PRE" == "1" ] && return 1
449
450        return 0
451}
452
[739fb00]453# Obtener los parámetros de red del servidor.
454function getNetworkSettings()
455{
456        # Variables globales definidas:
457        # - SERVERIP:   IP local de la interfaz por defecto.
458
459        local DEVICES
460        local dev
461
[0304465]462        echoAndLog "${FUNCNAME}(): Detecting network parameters"
[90b507d]463        SERVERIP="$ServidorAdm"
[739fb00]464        DEVICES="$(ip -o link show up | awk '!/loopback/ {sub(/:.*/,"",$2); print $2}')"
465        for dev in $DEVICES; do
466                [ -z "$SERVERIP" ] && SERVERIP=$(ip -o addr show dev $dev | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4)}')
467        done
468}
469
[a0867b37]470
471#####################################################################
472####### Funciones específicas de la instalación de Opengnsys
473#####################################################################
474
[5f21d34]475# Actualizar cliente OpenGnsys.
[295b4ab]476function updateClientFiles()
[45f1fe8]477{
[74cd321]478        local ENGINECFG=$INSTALL_TARGET/client/etc/engine.cfg
479
[a43e90d]480        # Actualizar ficheros del cliente.
[74cd321]481        backupFile $ENGINECFG
[0304465]482        echoAndLog "${FUNCNAME}(): Updating OpenGnsys Client files"
[45f1fe8]483        rsync --exclude .svn -irplt $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
484        if [ $? -ne 0 ]; then
485                errorAndLog "${FUNCNAME}(): error while updating client structure"
[51b179a]486                exit 1
[45f1fe8]487        fi
488        find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null
[a43e90d]489
490        # Actualizar librerías del motor de clonación.
[0304465]491        echoAndLog "${FUNCNAME}(): Updating OpenGnsys Cloning Engine files"
[51b179a]492        rsync --exclude .svn -irplt $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
[45f1fe8]493        if [ $? -ne 0 ]; then
494                errorAndLog "${FUNCNAME}(): error while updating engine files"
[51b179a]495                exit 1
[45f1fe8]496        fi
[a3855dc]497        # Actualizar fichero de configuración del motor de clonación.
[c40710e]498        if ! grep -q "^TZ" $ENGINECFG; then
[a3855dc]499                TZ=$(timedatectl status | awk -F"[:()]" '/Time.*zone/ {print $2}')
[c40710e]500                cat << EOT >> $ENGINECFG
[a3855dc]501# OpenGnsys Server timezone.
502TZ="${TZ// /}"
503EOT
504        fi
[8fc7ce1]505        if ! diff -q ${ENGINECFG}{,-LAST} &>/dev/null; then
[c40710e]506                NEWFILES="$NEWFILES $ENGINECFG"
507        else
508                rm -f ${ENGINECFG}-LAST
509        fi
[ec045b1]510        # Obtener URL para descargas adicionales.
511        DOWNLOADURL=$(oglivecli config download-url 2>/dev/null)
[a0081b7]512        DOWNLOADURL=${DOWNLOADURL:-"https://$OPENGNSYS_SERVER/trac/downloads"}
[a3855dc]513
[0304465]514        echoAndLog "${FUNCNAME}(): client files successfully updated"
[45f1fe8]515}
[4e51cb0]516
[3ce53a7]517# Configurar HTTPS y exportar usuario y grupo del servicio Apache.
518function apacheConfiguration ()
[4e51cb0]519{
[6f4d39b]520        local config template
521
[900be258]522        # Activar HTTPS (solo actualizando desde versiones anteriores a 1.0.2) y
523        #    activar módulo Rewrite (solo actualizaciones desde 1.0.x a 1.1.x).
[2e38f60]524        if [ -e $APACHECFGDIR/sites-available/opengnsys.conf ]; then
[0304465]525                echoAndLog "${FUNCNAME}(): Configuring Apache modules"
[3ce53a7]526                a2ensite default-ssl
527                a2enmod ssl
[900be258]528                a2enmod rewrite
[3ce53a7]529                a2ensite opengnsys
[5f21d34]530        elif [ -e $APACHECFGDIR/conf.modules.d ]; then
[0304465]531                echoAndLog "${FUNCNAME}(): Configuring Apache modules"
[5f21d34]532                sed -i '/rewrite/s/^#//' $APACHECFGDIR/*.conf
[3ce53a7]533        fi
[6f4d39b]534        # Actualizar configuración de Apache a partir de fichero de plantilla.
535        for config in $APACHECFGDIR/{,sites-available/}opengnsys.conf; do
536                # Elegir plantilla según versión de Apache.
537                if [ -n "$(apachectl -v | grep "2\.[0-2]")" ]; then
538                       template=$WORKDIR/opengnsys/server/etc/apache-prev2.4.conf.tmpl > $config
539                else
540                       template=$WORKDIR/opengnsys/server/etc/apache.conf.tmpl
[900be258]541                fi
[6f4d39b]542                sed -e "s,CONSOLEDIR,$INSTALL_TARGET/www,g" $template > $config
[900be258]543        done
544
545        # Reiniciar Apache.
[a37e5fc4]546        service=$APACHESERV; $STARTSERCICE
[900be258]547
[3ce53a7]548        # Variables de ejecución de Apache.
[4e51cb0]549        # - APACHE_RUN_USER
550        # - APACHE_RUN_GROUP
[2e38f60]551        if [ -f $APACHECFGDIR/envvars ]; then
552                source $APACHECFGDIR/envvars
[4e51cb0]553        fi
[2e38f60]554        APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
[de8bbb1]555        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
[4e51cb0]556}
557
[4b96166]558# Configurar servicio Rsync.
559function rsyncConfigure()
560{
561        local service
562
563        # Configurar acceso a Rsync.
564        if [ ! -f /etc/rsyncd.conf ]; then
[0304465]565                echoAndLog "${FUNCNAME}(): Configuring Rsync service"
[65baf16]566                NEWFILES="$NEWFILES /etc/rsyncd.conf"
[4b96166]567                sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENTUSER/g" \
568                    $WORKDIR/opengnsys/repoman/etc/rsyncd.conf.tmpl > /etc/rsyncd.conf
569                # Habilitar Rsync.
570                if [ -f /etc/default/rsync ]; then
571                        perl -pi -e 's/RSYNC_ENABLE=.*/RSYNC_ENABLE=inetd/' /etc/default/rsync
572                fi
573                if [ -f $INETDCFGDIR/rsync ]; then
574                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/rsync
575                else
576                        cat << EOT > $INETDCFGDIR/rsync
577service rsync
578{
579        disable = no
580        socket_type = stream
581        wait = no
582        user = root
583        server = $(which rsync)
584        server_args = --daemon
585        log_on_failure += USERID
586        flags = IPv6
587}
588EOT
589                fi
590                # Activar e iniciar Rsync.
591                service="rsync"  $ENABLESERVICE
[ab7f563]592                service="xinetd"
593                $ENABLESERVICE; $STARTSERVICE
[4b96166]594        fi
595}
596
[5f21d34]597# Copiar ficheros del OpenGnsys Web Console.
[a0867b37]598function updateWebFiles()
599{
[2b793a8]600        local ERRCODE COMPATDIR f
601
[a0867b37]602        echoAndLog "${FUNCNAME}(): Updating web files..."
[2b793a8]603
604        # Copiar los ficheros nuevos conservando el archivo de configuración de acceso.
605        backupFile $INSTALL_TARGET/www/controlacceso.php
606        mv $INSTALL_TARGET/www $INSTALL_TARGET/WebConsole
[1db2ed8]607        rsync --exclude .svn -irplt $WORKDIR/opengnsys/admin/WebConsole $INSTALL_TARGET
[2b793a8]608        ERRCODE=$?
609        mv $INSTALL_TARGET/WebConsole $INSTALL_TARGET/www
[1635f45]610        rm -fr $INSTALL_TARGET/www/xajax
[900be258]611        unzip -o $WORKDIR/opengnsys/admin/slim-2.6.1.zip -d $INSTALL_TARGET/www/rest
[8b8e948]612        unzip -o $WORKDIR/opengnsys/admin/swagger-ui-2.2.5.zip -d $INSTALL_TARGET/www/rest
[d655cc4]613        if [ $ERRCODE != 0 ]; then
[a0867b37]614                errorAndLog "${FUNCNAME}(): Error updating web files."
615                exit 1
616        fi
[2b793a8]617        restoreFile $INSTALL_TARGET/www/controlacceso.php
618
[1a2fa9d8]619        # Cambiar acceso a protocolo HTTPS.
620        if grep -q "http://" $INSTALL_TARGET/www/controlacceso.php 2>/dev/null; then
621                echoAndLog "${FUNCNAME}(): updating web access file"
622                perl -pi -e 's!http://!https://!g' $INSTALL_TARGET/www/controlacceso.php
623                NEWFILES="$NEWFILES $INSTALL_TARGET/www/controlacceso.php"
624        fi
625
[2b793a8]626        # Compatibilidad con dispositivos móviles.
627        COMPATDIR="$INSTALL_TARGET/www/principal"
628        for f in acciones administracion aula aulas hardwares imagenes menus repositorios softwares; do
629                sed 's/clickcontextualnodo/clicksupnodo/g' $COMPATDIR/$f.php > $COMPATDIR/$f.device.php
630        done
[d70a45f]631        cp -a $COMPATDIR/imagenes.device.php $COMPATDIR/imagenes.device4.php
[2b793a8]632
[0645906]633        # Fichero de log de la API REST.
634        touch $INSTALL_TARGET/log/{ogagent,rest,remotepc}.log
[0304465]635        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/log/{ogagent,rest,remotepc}.log
[2b793a8]636
[0304465]637        echoAndLog "${FUNCNAME}(): Web files successfully updated"
[a0867b37]638}
639
[ec045b1]640# Copiar ficheros en la zona de descargas de OpenGnsys Web Console.
641function updateDownloadableFiles()
642{
[0304465]643        local FILENAME=ogagentpkgs-$NEWVERSION.tar.gz
[ec045b1]644        local TARGETFILE=$WORKDIR/$FILENAME
645
646        # Descargar archivo comprimido, si es necesario.
647        if [ -s $PROGRAMDIR/$FILENAME ]; then
648                echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
649                mv $PROGRAMDIR/$FILENAME $TARGETFILE
650        else
651                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
652                wget $DOWNLOADURL/$FILENAME -O $TARGETFILE
653        fi
654        if [ ! -s $TARGETFILE ]; then
655                errorAndLog "${FUNCNAME}(): Cannot download $FILENAME"
656                return 1
657        fi
658
659        # Descomprimir fichero en zona de descargas.
660        tar xvzf $TARGETFILE -C $INSTALL_TARGET/www/descargas
661        if [ $? != 0 ]; then
[0304465]662                errorAndLog "${FUNCNAME}(): Error uncompressing archive $FILENAME"
[ec045b1]663                exit 1
664        fi
665}
666
[72134d5]667# Copiar carpeta de Interface
[64dd765]668function updateInterfaceAdm()
[72134d5]669{
[27dc5ff]670        local errcode=0
[2b793a8]671
[72134d5]672        # Crear carpeta y copiar Interface
673        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
674        mv $INSTALL_TARGET/client/interfaceAdm $INSTALL_TARGET/client/Interface
675        rsync --exclude .svn -irplt $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client
[27dc5ff]676        errcoce=$?
[72134d5]677        mv $INSTALL_TARGET/client/Interface $INSTALL_TARGET/client/interfaceAdm
[27dc5ff]678        if [ $errcode -ne 0 ]; then
[72134d5]679                echoAndLog "${FUNCNAME}(): error while updating admin interface"
680                exit 1
681        fi
[0304465]682        echoAndLog "${FUNCNAME}(): Admin interface successfully updated"
[72134d5]683}
[a0867b37]684
[5d6bf97]685# Crear documentación Doxygen para la consola web.
686function makeDoxygenFiles()
687{
688        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
689        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
690                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
691        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
[0304465]692                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files"
[5d6bf97]693                return 1
694        fi
[45f1fe8]695        rm -fr "$INSTALL_TARGET/www/api"
[15b2a4e]696        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
697        rm -fr $INSTALL_TARGET/www/{man,perlmod,rtf}
[0304465]698        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully"
[5d6bf97]699}
700
701
[a0867b37]702# Crea la estructura base de la instalación de opengnsys
703function createDirs()
704{
[eb9424f]705        # Crear estructura de directorios.
[a0867b37]706        echoAndLog "${FUNCNAME}(): creating directory paths in ${INSTALL_TARGET}"
[7bb72f7]707        local dir
708
[cfad47b]709        mkdir -p ${INSTALL_TARGET}/{bin,doc,etc,lib,sbin,www}
[d7ece95]710        mkdir -p ${INSTALL_TARGET}/{client,images/groups}
[a0867b37]711        mkdir -p ${INSTALL_TARGET}/log/clients
[eb9424f]712        ln -fs ${INSTALL_TARGET}/log /var/log/opengnsys
[7bb72f7]713        # Detectar directorio de instalación de TFTP.
714        if [ ! -L ${INSTALL_TARGET}/tftpboot ]; then
715                for dir in /var/lib/tftpboot /srv/tftp; do
716                        [ -d $dir ] && ln -fs $dir ${INSTALL_TARGET}/tftpboot
717                done
718        fi
[663cd905]719        mkdir -p $INSTALL_TARGET/tftpboot/menu.lst/examples
[a0867b37]720        if [ $? -ne 0 ]; then
721                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
722                return 1
723        fi
[663cd905]724        ! [ -f $INSTALL_TARGET/tftpboot/menu.lst/templates/00unknown ] && mv $INSTALL_TARGET/tftpboot/menu.lst/templates/* $INSTALL_TARGET/tftpboot/menu.lst/examples
[a0867b37]725
[eb9424f]726        # Crear usuario ficticio.
727        if id -u $OPENGNSYS_CLIENTUSER &>/dev/null; then
728                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENTUSER\" is already created"
729        else
[5f21d34]730                echoAndLog "${FUNCNAME}(): creating OpenGnsys user"
[eb9424f]731                useradd $OPENGNSYS_CLIENTUSER 2>/dev/null
732                if [ $? -ne 0 ]; then
[5f21d34]733                        errorAndLog "${FUNCNAME}(): error creating OpenGnsys user"
[eb9424f]734                        return 1
735                fi
736        fi
737
[57f7e9c]738        # Mover el fichero de registro al directorio de logs.
739        echoAndLog "${FUNCNAME}(): moving update log file"
740        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
[7669bca]741        chmod 600 $LOG_FILE
[57f7e9c]742
[a0867b37]743        echoAndLog "${FUNCNAME}(): directory paths created"
744        return 0
745}
746
[566e84f]747# Actualización incremental de la BD (versión actaul a actaul+1, hasta final-1 a final).
748function updateDatabase()
749{
750        local DBDIR="$WORKDIR/opengnsys/admin/Database"
751        local file FILES=""
752
753        echoAndLog "${FUNCNAME}(): looking for database updates"
754        pushd $DBDIR >/dev/null
755        # Bucle de actualización incremental desde versión actual a la final.
756        for file in $OPENGNSYS_DATABASE-*-*.sql; do
757                case "$file" in
758                        $OPENGNSYS_DATABASE-$OLDVERSION-$NEWVERSION.sql)
759                                # Actualización única de versión inicial y final.
760                                FILES="$FILES $file"
761                                break
762                                ;;
763                        $OPENGNSYS_DATABASE-*-postinst.sql)
764                                # Ignorar fichero específico de post-instalación.
765                                ;;
766                        $OPENGNSYS_DATABASE-$OLDVERSION-*.sql)
767                                # Actualización de versión n a n+1.
768                                FILES="$FILES $file"
769                                OLDVERSION="$(echo $file | cut -f3 -d-)"
770                                ;;
771                        $OPENGNSYS_DATABASE-*-$NEWVERSION.sql)
772                                # Última actualización de versión final-1 a final.
773                                if [ -n "$FILES" ]; then
774                                        FILES="$FILES $file"
775                                        break
776                                fi
777                                ;;
778                esac
779        done
780        # Aplicar posible actualización propia para la versión final.
781        file=$OPENGNSYS_DATABASE-$NEWVERSION.sql
782        if [ -n "$FILES" -o "$OLDVERSION" = "$NEWVERSION" -a -r $file ]; then
783                FILES="$FILES $file"
784        fi
785
786        popd >/dev/null
787        if [ -n "$FILES" ]; then
788                for file in $FILES; do
[0cfe47a]789                        importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $DBDIR/$file
[566e84f]790                done
791                echoAndLog "${FUNCNAME}(): database is update"
792        else
793                echoAndLog "${FUNCNAME}(): database unchanged"
794        fi
795}
796
[a0867b37]797# Copia ficheros de configuración y ejecutables genéricos del servidor.
[64dd765]798function updateServerFiles()
[bb30a50]799{
[c1e00e4]800        # No copiar ficheros del antiguo cliente Initrd
[873cf1e]801        local SOURCES=( repoman/bin \
[c1e00e4]802                        server/bin \
[3e7d77b]803                        server/lib \
[42a0e41]804                        admin/Sources/Services/ogAdmServerAux \
805                        admin/Sources/Services/ogAdmRepoAux \
[873cf1e]806                        server/tftpboot \
[bb30a50]807                        installer/opengnsys_uninstall.sh \
[6777e3e]808                        installer/opengnsys_export.sh \
809                        installer/opengnsys_import.sh \
[873cf1e]810                        doc )
811        local TARGETS=( bin \
812                        bin \
[3e7d77b]813                        lib \
[cdad332]814                        sbin/ogAdmServerAux \
815                        sbin/ogAdmRepoAux \
[873cf1e]816                        tftpboot \
[9a2c0f9d]817                        lib/opengnsys_uninstall.sh \
[6777e3e]818                        lib/opengnsys_export.sh \
819                        lib/opengnsys_import.sh \
[873cf1e]820                        doc )
[a0867b37]821
822        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
823                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
824                exit 1
825        fi
826
827        echoAndLog "${FUNCNAME}(): updating files in server directories"
828        pushd $WORKDIR/opengnsys >/dev/null
829        local i
830        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
[27dc5ff]831                if [ -d "$INSTALL_TARGET/${TARGETS[i]}" ]; then
[4057c5d]832                        rsync --exclude .svn -irplt "${SOURCES[i]}" $(dirname $(readlink -e "$INSTALL_TARGET/${TARGETS[i]}"))
[aa36857]833                else
[56f100f]834                        rsync -irplt "${SOURCES[i]}" $(readlink -m "$INSTALL_TARGET/${TARGETS[i]}")
[aa36857]835                fi
[a0867b37]836        done
837        popd >/dev/null
[df3cd7f]838        NEWFILES=""             # Ficheros de configuración que han cambiado de formato.
[f80f839]839        if grep -q 'pxelinux.0' /etc/dhcp*/dhcpd*.conf; then
[df3cd7f]840                echoAndLog "${FUNCNAME}(): updating DHCP files"
[f80f839]841                perl -pi -e 's/pxelinux.0/grldr/' /etc/dhcp*/dhcpd*.conf
[a37e5fc4]842                service=$DHCPSERV; $STARTSERVICE
[df3cd7f]843                NEWFILES="/etc/dhcp*/dhcpd*.conf"
844        fi
[d372e6e]845        if ! diff -q $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys 2>/dev/null; then
[df3cd7f]846                echoAndLog "${FUNCNAME}(): updating new init file"
847                backupFile /etc/init.d/opengnsys
848                cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
849                NEWFILES="$NEWFILES /etc/init.d/opengnsys"
850        fi
[1a2fa9d8]851        if egrep -q "(UrlMsg=.*msgbrowser.php)|(UrlMenu=http://)" $INSTALL_TARGET/client/etc/ogAdmClient.cfg 2>/dev/null; then
[df3cd7f]852                echoAndLog "${FUNCNAME}(): updating new client config file"
853                backupFile $INSTALL_TARGET/client/etc/ogAdmClient.cfg
[1a2fa9d8]854                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
[df3cd7f]855                NEWFILES="$NEWFILES $INSTALL_TARGET/client/etc/ogAdmClient.cfg"
[f80f839]856        fi
[a3855dc]857
[9ee62ad]858        echoAndLog "${FUNCNAME}(): updating cron files"
[db9e706]859        [ ! -f /etc/cron.d/opengnsys ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
860        [ ! -f /etc/cron.d/torrentcreator ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
861        [ ! -f /etc/cron.d/torrenttracker ] && echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
[dc762088]862        [ ! -f /etc/cron.d/imagedelete ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
[0645906]863        [ ! -f /etc/cron.d/ogagentqueue ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/ogagentqueue.cron ] && $INSTALL_TARGET/bin/ogagentqueue.cron" > /etc/cron.d/ogagentqueue
[0304465]864        echoAndLog "${FUNCNAME}(): server files successfully updated"
[a0867b37]865}
866
867####################################################################
868### Funciones de compilación de código fuente de servicios
869####################################################################
870
[dde65c7]871# Mueve el fichero del nuevo servicio si es distinto al del directorio destino.
872function moveNewService()
873{
874        local service
875
876        # Recibe 2 parámetros: fichero origen y directorio destino.
877        [ $# == 2 ] || return 1
[ddcb0cf]878        [ -f  $1 -a -d $2 ] || return 1
[dde65c7]879
880        # Comparar los ficheros.
[ddcb0cf]881        if ! diff -q $1 $2/$(basename $1) &>/dev/null; then
[dde65c7]882                # Parar los servicios si fuese necesario.
883                [ -z "$NEWSERVICES" ] && service="opengnsys" $STOPSERVICE
884                # Nuevo servicio.
885                NEWSERVICES="$NEWSERVICES $(basename $1)"
886                # Mover el nuevo fichero de servicio
887                mv $1 $2
888        fi
889}
890
891
[bb30a50]892# Recompilar y actualiza los serivicios y clientes.
[64dd765]893function compileServices()
[a0867b37]894{
[bb30a50]895        local hayErrores=0
896
[5f21d34]897        # Compilar OpenGnsys Server
898        echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Admin Server"
[bb30a50]899        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
[dde65c7]900        make && moveNewService ogAdmServer $INSTALL_TARGET/sbin
[bb30a50]901        if [ $? -ne 0 ]; then
[5f21d34]902                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Server"
[bb30a50]903                hayErrores=1
904        fi
905        popd
[5f21d34]906        # Compilar OpenGnsys Repository Manager
907        echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Repository Manager"
[bb30a50]908        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo
[dde65c7]909        make && moveNewService ogAdmRepo $INSTALL_TARGET/sbin
[bb30a50]910        if [ $? -ne 0 ]; then
[5f21d34]911                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Repository Manager"
[bb30a50]912                hayErrores=1
913        fi
914        popd
[f9b5714]915        # Actualizar o insertar clave de acceso REST en el fichero de configuración del repositorio.
[f6284d2]916        grep -q '^ApiToken=' $INSTALL_TARGET/etc/ogAdmRepo.cfg && \
917                sed -i "s/^ApiToken=.*$/ApiToken=$REPOKEY/" $INSTALL_TARGET/etc/ogAdmRepo.cfg || \
918                sed -i "$ a\ApiToken=$REPOKEY/" $INSTALL_TARGET/etc/ogAdmRepo.cfg
[5f21d34]919        # Compilar OpenGnsys Agent
[0304465]920        echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Server Agent"
[bb30a50]921        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
[dde65c7]922        make && moveNewService ogAdmAgent $INSTALL_TARGET/sbin
[bb30a50]923        if [ $? -ne 0 ]; then
[0304465]924                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Server Agent"
[bb30a50]925                hayErrores=1
926        fi
927        popd
928
[5f21d34]929        # Compilar OpenGnsys Client
930        echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Client"
[72134d5]931        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
[e473667]932        make && mv ogAdmClient $INSTALL_TARGET/client/bin
[a0867b37]933        if [ $? -ne 0 ]; then
[5f21d34]934                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Client"
[a0867b37]935                hayErrores=1
936        fi
937        popd
938
939        return $hayErrores
940}
941
942
943####################################################################
[5f21d34]944### Funciones instalacion cliente OpenGnsys
[a0867b37]945####################################################################
946
[5f21d34]947# Actualizar cliente OpenGnsys
[c1e00e4]948function updateClient()
949{
[dced872]950        #local FILENAME=ogLive-precise-3.2.0-23-generic-r5159.iso       # 1.1.0-rc6 (old)
951        local FILENAME=ogLive-xenial-4.8.0-39-generic-amd64-r5331.iso   # 1.1.0-rc6
[0b85cc93]952        local SOURCEFILE=$DOWNLOADURL/$FILENAME
[0496417]953        local TARGETFILE=$(oglivecli config download-dir)/$FILENAME
[0b85cc93]954        local SOURCELENGTH
955        local TARGETLENGTH
[0496417]956        local OGINITRD
[a63345ac]957        local SAMBAPASS
[0b85cc93]958
[0496417]959        # Comprobar si debe convertirse el antiguo cliente al nuevo formato ogLive.
960        if oglivecli check | grep -q "oglivecli convert"; then
961                echoAndLog "${FUNCNAME}(): Converting OpenGnsys Client to default ogLive"
962                oglivecli convert
963        fi
[0b85cc93]964        # Comprobar si debe actualizarse el cliente.
[c3cc6b0]965        SOURCELENGTH=$(LANG=C wget --spider $SOURCEFILE 2>&1 | awk '/Length:/ {print $2}')
[0496417]966        TARGETLENGTH=$(stat -c "%s" $TARGETFILE 2>/dev/null)
[d4e90c1]967        [ -z $TARGETLENGTH ] && TARGETLENGTH=0
[0b85cc93]968        if [ "$SOURCELENGTH" != "$TARGETLENGTH" ]; then
[ec045b1]969                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
[0496417]970                oglivecli download $FILENAME
[0b85cc93]971                if [ ! -s $TARGETFILE ]; then
[ec045b1]972                        errorAndLog "${FUNCNAME}(): Error downloading $FILENAME"
[0b85cc93]973                        return 1
974                fi
[1893b9d]975                # Actaulizar la imagen ISO del ogclient.
[0304465]976                echoAndLog "${FUNCNAME}(): Updatting ogLive client"
[0496417]977                oglivecli install $FILENAME
[e1c01217]978               
[8b2da718]979                CLIENTUPDATED=${FILENAME%.*}
[ee4beb4]980
[0304465]981                echoAndLog "${FUNCNAME}(): ogLive successfully updated"
[0b85cc93]982        else
[65baf16]983                # Si no existe, crear el fichero de claves de Rsync.
984                if [ ! -f /etc/rsyncd.secrets ]; then
[ec045b1]985                        echoAndLog "${FUNCNAME}(): Restoring ogLive access key"
[0496417]986                        OGINITRD=$(oglivecli config install-dir)/$(jq -r ".oglive[.default].directory")/oginitrd.img
[65baf16]987                        SAMBAPASS=$(gzip -dc $OGINITRD | \
988                                    cpio -i --to-stdout scripts/ogfunctions 2>&1 | \
989                                    grep "^[    ].*OPTIONS=" | \
990                                    sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
[0496417]991                        echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | setsmbpass
[65baf16]992                else
[ec045b1]993                        echoAndLog "${FUNCNAME}(): ogLive is already updated"
[65baf16]994                fi
[04e5d96]995                # Versión del ogLive instalado.
996                echo "${FILENAME%.*}" > $INSTALL_TARGET/doc/veroglive.txt
[c1e00e4]997        fi
998}
[a0867b37]999
[5b95ab6]1000# Comprobar permisos y ficheros.
1001function checkFiles()
1002{
1003        # Comprobar permisos adecuados.
1004        if [ -x $INSTALL_TARGET/bin/checkperms ]; then
[0304465]1005                echoAndLog "${FUNCNAME}(): Checking permissions"
[5b95ab6]1006                OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENTUSER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" $INSTALL_TARGET/bin/checkperms
1007        fi
1008
1009        # Eliminamos el fichero de estado del tracker porque es incompatible entre los distintos paquetes
1010        if [ -f /tmp/dstate ]; then
[0304465]1011                echoAndLog "${FUNCNAME}(): Deleting unused files"
[5b95ab6]1012                rm -f /tmp/dstate
1013        fi
1014}
1015
[eb9424f]1016# Resumen de actualización.
1017function updateSummary()
1018{
1019        # Actualizar fichero de versión y revisión.
1020        local VERSIONFILE="$INSTALL_TARGET/doc/VERSION.txt"
[57f7e9c]1021        local REVISION=$(LANG=C svn info $SVN_URL|awk '/Rev:/ {print "r"$4}')
[eb9424f]1022
[5f21d34]1023        [ -f $VERSIONFILE ] || echo "OpenGnsys" >$VERSIONFILE
[eb9424f]1024        perl -pi -e "s/($| r[0-9]*)/ $REVISION/" $VERSIONFILE
1025
1026        echo
[5f21d34]1027        echoAndLog "OpenGnsys Update Summary"
[df3cd7f]1028        echo       "========================"
1029        echoAndLog "Project version:                  $(cat $VERSIONFILE)"
[57f7e9c]1030        echoAndLog "Update log file:                  $LOG_FILE"
[df3cd7f]1031        if [ -n "$NEWFILES" ]; then
[a3855dc]1032                echoAndLog "Check new config files:           $(echo $NEWFILES)"
[df3cd7f]1033        fi
[dde65c7]1034        if [ -n "$NEWSERVICES" ]; then
1035                echoAndLog "New compiled services:            $(echo $NEWSERVICES)"
1036                # Indicar si se debe reiniciar servicios manualmente o usando el Cron.
1037                [ -f /etc/default/opengnsys ] && source /etc/default/opengnsys
1038                if [ "$RUN_CRONJOB" == "no" ]; then
[0304465]1039                        echoAndLog "        WARNING: you must to restart OpenGnsys services manually"
[dde65c7]1040                else
[0304465]1041                        echoAndLog "        New OpenGnsys services will be restarted by the cronjob"
[dde65c7]1042                fi
1043        fi
[8b2da718]1044        echoAndLog "Warnings:"
[0304465]1045        echoAndLog " - You must to clear web browser cache before loading OpenGnsys page"
1046        echoAndLog " - Generated new key to access Repository REST API (file ogAdmRepo.cfg)"
[8b2da718]1047        if [ -n "$CLIENTUPDATED" ]; then
1048                echoAndLog " - ogLive Client is updated to: $CLIENTUPDATED"
1049        fi
[21372e8]1050        if [ -n "$MYSQLCONFIG" ]; then
[0304465]1051                echoAndLog " - MySQL must be reconfigured, run next code as DB root user and restart service:"
[21372e8]1052                echoAndLog "      $MYSQLCONFIG"
1053        fi
[eb9424f]1054        echo
1055}
1056
1057
[a0867b37]1058
1059#####################################################################
[5f21d34]1060####### Proceso de actualización de OpenGnsys
[a0867b37]1061#####################################################################
1062
1063
[5f21d34]1064echoAndLog "OpenGnsys update begins at $(date)"
[a0867b37]1065
[bb30a50]1066pushd $WORKDIR
1067
[27dc5ff]1068# Comprobar si hay conexión y detectar parámetros de red por defecto.
1069checkNetworkConnection
1070if [ $? -ne 0 ]; then
1071        errorAndLog "Error connecting to server. Causes:"
[0304465]1072        errorAndLog " - Network is unreachable, check device parameters"
1073        errorAndLog " - You are inside a private network, configure the proxy service"
1074        errorAndLog " - Server is temporally down, try again later"
[27dc5ff]1075        exit 1
1076fi
[739fb00]1077getNetworkSettings
[27dc5ff]1078
[0304465]1079# Comprobar si se intanta actualizar a una versión anterior.
1080checkVersion
1081if [ $? -ne 0 ]; then
1082        errorAndLog "Cannot downgrade to an older version ($OLDVERSION to $NEWVERSION)"
1083        errorAndLog "You must to uninstall OpenGnsys and install desired release"
1084        exit 1
1085fi
1086
[64dd765]1087# Comprobar auto-actualización del programa.
1088if [ "$PROGRAMDIR" != "$INSTALL_TARGET/bin" ]; then
1089        checkAutoUpdate
1090        if [ $? -ne 0 ]; then
[0304465]1091                echoAndLog "OpenGnsys updater has been overwritten"
1092                echoAndLog "Please, rerun this script"
[64dd765]1093                exit
1094        fi
1095fi
1096
[db9e706]1097# Detectar datos de auto-configuración del instalador.
1098autoConfigure
1099
[bb30a50]1100# Instalar dependencias.
[d70a45f]1101installDependencies ${DEPENDENCIES[*]}
[a0867b37]1102if [ $? -ne 0 ]; then
[0304465]1103        errorAndLog "Error: you must to install all needed dependencies"
[a0867b37]1104        exit 1
1105fi
1106
[5f21d34]1107# Arbol de directorios de OpenGnsys.
[a0867b37]1108createDirs ${INSTALL_TARGET}
1109if [ $? -ne 0 ]; then
[0304465]1110        errorAndLog "Error while creating directory paths"
[a0867b37]1111        exit 1
1112fi
1113
1114# Si es necesario, descarga el repositorio de código en directorio temporal
1115if [ $USESVN -eq 1 ]; then
1116        svnExportCode $SVN_URL
1117        if [ $? -ne 0 ]; then
[0304465]1118                errorAndLog "Error while getting code from svn server"
[a0867b37]1119                exit 1
1120        fi
1121else
1122        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
1123fi
1124
[21372e8]1125# Comprobar configuración de MySQL.
1126checkMysqlConfig $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD
1127
[566e84f]1128# Actualizar la BD.
1129updateDatabase
[295b4ab]1130
1131# Actualizar ficheros complementarios del servidor
[a0867b37]1132updateServerFiles
1133if [ $? -ne 0 ]; then
[5f21d34]1134        errorAndLog "Error updating OpenGnsys Server files"
[a0867b37]1135        exit 1
1136fi
1137
[be49575]1138# Configurar Rsync.
1139rsyncConfigure
1140
[295b4ab]1141# Actualizar ficheros del cliente
1142updateClientFiles
1143updateInterfaceAdm
[45f1fe8]1144
[295b4ab]1145# Actualizar páqinas web
[3ce53a7]1146apacheConfiguration
[a0867b37]1147updateWebFiles
1148if [ $? -ne 0 ]; then
[5f21d34]1149        errorAndLog "Error updating OpenGnsys Web Admin files"
[a0867b37]1150        exit 1
1151fi
[ec045b1]1152# Actaulizar ficheros descargables.
1153updateDownloadableFiles
[5d6bf97]1154# Generar páginas Doxygen para instalar en el web
1155makeDoxygenFiles
[a0867b37]1156
[bb30a50]1157# Recompilar y actualizar los servicios del sistema
1158compileServices
1159
1160# Actaulizar ficheros auxiliares del cliente
[a0867b37]1161updateClient
1162if [ $? -ne 0 ]; then
[0304465]1163        errorAndLog "Error updating client files"
[a0867b37]1164        exit 1
1165fi
1166
[5b95ab6]1167# Comprobar permisos y ficheros.
1168checkFiles
[3320409]1169
[eb9424f]1170# Mostrar resumen de actualización.
1171updateSummary
1172
[a0867b37]1173#rm -rf $WORKDIR
[5f21d34]1174echoAndLog "OpenGnsys update finished at $(date)"
[a0867b37]1175
1176popd
1177
Note: See TracBrowser for help on using the repository browser.