close Warning: Failed to sync with repository "ogBrowser-Git": (1366, "Incorrect string value: '\\xF0\\x9F\\x93\\xA6 I...' for column 'message' at row 1"); repository information may be out of date. Look in the Trac log for more information including mitigation strategies.

source: installer/opengnsys_update.sh @ 82dbaff

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 82dbaff was 884b6ce, checked in by Ramón M. Gómez <ramongomez@…>, 7 years ago

#840: Usar repositorio de GitHub? en instalación y actualización.

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