source: installer/opengnsys_update.sh @ 0433dbe

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 0433dbe was b411a0f, checked in by Ramón M. Gómez <ramongomez@…>, 6 years ago

#886: Backward-compatible with JQ version 1.4

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