source: installer/opengnsys_update.sh @ 046004d

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 046004d was a3a1ff2, checked in by Ramón M. Gómez <ramongomez@…>, 7 years ago

#840: Checking permissions and directories after Git downloads.

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