source: installer/opengnsys_update.sh @ 1736503

Last change on this file since 1736503 was e98f7d1, checked in by Irina Gómez <irinagomez@…>, 4 years ago

#1026 The installation and upgrade scripts display messages with the OpenGnsys version prerequisites; in case of update, they also show the current version.

  • Property mode set to 100755
File size: 48.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
[fd45e9a]32#@version 1.1.1a - Elegir versión a actualizar.
33#@author  Ramón Gómez - ETSII Univ. Sevilla
34#@date    2019/12/13
[a0867b37]35#*/
36
37
[1175096]38####  AVISO: NO EDITAR variables de configuración.
39####  WARNING: DO NOT EDIT configuration variables.
40INSTALL_TARGET=/opt/opengnsys           # Directorio de instalación
[ec045b1]41PATH=$PATH:$INSTALL_TARGET/bin
[295b4ab]42OPENGNSYS_CLIENTUSER="opengnsys"        # Usuario Samba
43
44
[a0867b37]45# Sólo ejecutable por usuario root
[6ef01d9]46if [ "$(whoami)" != 'root' ]; then
[a0867b37]47        echo "ERROR: this program must run under root privileges!!"
48        exit 1
49fi
[5f21d34]50# Error si OpenGnsys no está instalado (no existe el directorio del proyecto)
[4e51cb0]51if [ ! -d $INSTALL_TARGET ]; then
[5f21d34]52        echo "ERROR: OpenGnsys is not installed, cannot update!!"
[4e51cb0]53        exit 1
54fi
[4972d15]55
56source $INSTALL_TARGET/lib/ogfunctions.sh || exit 1
57
[e98f7d1]58echo -n "Current version: "
59if [ -r $INSTALL_TARGET/doc/VERSION.json ]; then
60        jq -j '"OpenGnsys", .version, " ", .release' $INSTALL_TARGET/doc/VERSION.json
61else
62        cat $INSTALL_TARGET/doc/VERSION.txt
63fi
64
65echo -e "\nThe OpenGnsys version 1.2.0 was tested with full functionality on Ubuntu 18.04 with PHP 7.2."
66echo " * If the update is made from a version prior to 1.1.1c, you must disable strict mode in mysql by adding in the configuration file: sql_mode = NO_ENGINE_SUBSTITUTION"
67echo " * If you are going to perform an update from version 1.1.0, it is necessary to start with the operating system, moving it from Ubuntu 16.04 to Ubuntu 18.04, and then perform the OpenGnsys update."
68
69echo -e -n "\nDo you want to continue? [y/N]: "
70read -r GO_ON
71if [ "${GO_ON^^}" != "Y" ]; then
72        echo "We left the installation." && exit
73fi
74
[1175096]75# Cargar configuración de acceso a la base de datos.
[4972d15]76if [ -r $INSTALL_TARGET/etc/ogserver.json ]; then
77        source_json_config $INSTALL_TARGET/etc/ogserver.json
78elif [ -r $INSTALL_TARGET/etc/ogserver.cfg ]; then
[c583144]79        source $INSTALL_TARGET/etc/ogserver.cfg
[03f813b]80elif [ -r $INSTALL_TARGET/etc/ogAdmServer.cfg ]; then
81        source $INSTALL_TARGET/etc/ogAdmServer.cfg
[1175096]82fi
[42a0e41]83OPENGNSYS_DATABASE=${OPENGNSYS_DATABASE:-"$CATALOG"}            # Base de datos
[1175096]84OPENGNSYS_DBUSER=${OPENGNSYS_DBUSER:-"$USUARIO"}                # Usuario de acceso
85OPENGNSYS_DBPASSWORD=${OPENGNSYS_DBPASSWORD:-"$PASSWORD"}       # Clave del usuario
86if [ -z "$OPENGNSYS_DATABASE" -o -z "$OPENGNSYS_DBUSER" -o -z "$OPENGNSYS_DBPASSWORD" ]; then
87        echo "ERROR: set OPENGNSYS_DATABASE, OPENGNSYS_DBUSER and OPENGNSYS_DBPASSWORD"
88        echo "       variables, and run this script again."
[0304465]89        exit 1
[1175096]90fi
[a0867b37]91
[884b6ce]92# Comprobar si se ha descargado el paquete comprimido (REMOTE=0) o sólo el instalador (REMOTE=1).
[a0867b37]93PROGRAMDIR=$(readlink -e $(dirname "$0"))
[64dd765]94PROGRAMNAME=$(basename "$0")
[a0081b7]95OPENGNSYS_SERVER="opengnsys.es"
[a0867b37]96if [ -d "$PROGRAMDIR/../installer" ]; then
[884b6ce]97        REMOTE=0
[a0867b37]98else
[884b6ce]99        REMOTE=1
[a0867b37]100fi
101
102WORKDIR=/tmp/opengnsys_update
103mkdir -p $WORKDIR
104
[42a0e41]105# Registro de incidencias.
106OGLOGFILE=$INSTALL_TARGET/log/${PROGRAMNAME%.sh}.log
[57f7e9c]107LOG_FILE=/tmp/$(basename $OGLOGFILE)
[a0867b37]108
109
110
111#####################################################################
112####### Algunas funciones útiles de propósito general:
113#####################################################################
[295b4ab]114
[db9e706]115# Generar variables de configuración del actualizador
116# Variables globales:
[2e38f60]117# - OSDISTRIB - distribución Linux
[db9e706]118# - DEPENDENCIES - array de dependencias que deben estar instaladas
119# - UPDATEPKGLIST, INSTALLPKGS, CHECKPKG - comandos para gestión de paquetes
[3b0436d]120# - APACHECFGDIR, APACHESERV, PHPFPMSERV, DHCPSERV, MYSQLSERV, MYSQLCFGDIR, INETDCFGDIR - configuración y servicios
[ec536c6]121
[db9e706]122function autoConfigure()
123{
[a37e5fc4]124        local service
[2e38f60]125
[a37e5fc4]126        # Detectar sistema operativo del servidor (compatible con fichero os-release y con LSB).
127        if [ -f /etc/os-release ]; then
128                source /etc/os-release
129                OSDISTRIB="$ID"
130                OSVERSION="$VERSION_ID"
131        else
132                OSDISTRIB=$(lsb_release -is 2>/dev/null)
133                OSVERSION=$(lsb_release -rs 2>/dev/null)
134        fi
135        # Convertir distribución a minúsculas y obtener solo el 1er número de versión.
136        OSDISTRIB="${OSDISTRIB,,}"
137        OSVERSION="${OSVERSION%%.*}"
138
139        # Configuración según la distribución de Linux.
140        if [ -f /etc/debian_version ]; then
[884b6ce]141                # Distribución basada en paquetes Deb.
[0e3e167]142                DEPENDENCIES=( curl rsync btrfs-tools procps arp-scan realpath php-curl gettext moreutils jq wakeonlan udpcast libev-dev libjansson-dev libssl-dev shim-signed grub-efi-amd64-signed php-fpm gawk libdbi-dev libdbi1 libdbd-mysql automake liblz4-tool )
[42c7e5f]143                # Paquete correcto para realpath.
144                [ -z "$(apt-cache pkgnames realpath)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//realpath/coreutils} )
[0304465]145                UPDATEPKGLIST="add-apt-repository -y ppa:ondrej/php; apt-get update"
[a37e5fc4]146                INSTALLPKGS="apt-get -y install"
147                DELETEPKGS="apt-get -y purge"
[db9e706]148                CHECKPKG="dpkg -s \$package 2>/dev/null | grep -q \"Status: install ok\""
[4b96166]149                if which service &>/dev/null; then
150                        STARTSERVICE="eval service \$service restart"
[dde65c7]151                        STOPSERVICE="eval service \$service stop"
[a37e5fc4]152                        SERVICESTATUS="eval service \$service status"
[4b96166]153                else
154                        STARTSERVICE="eval /etc/init.d/\$service restart"
[dde65c7]155                        STOPSERVICE="eval /etc/init.d/\$service stop"
[a37e5fc4]156                        SERVICESTATUS="eval /etc/init.d/\$service status"
[4b96166]157                fi
[2c69d57]158                ENABLESERVICE="eval systemctl enable \$service.service"
[9215580]159                APACHEENABLEMODS="ssl rewrite proxy_fcgi fastcgi actions alias"
160                APACHEDISABLEMODS="php"
[2e38f60]161                APACHEUSER="www-data"
162                APACHEGROUP="www-data"
[3b0436d]163                MYSQLCFGDIR=/etc/mysql/mysql.conf.d
164                MYSQLSERV="mysql"
[ec536c6]165                PHPFPMSERV="php-fpm"
[65baf16]166                INETDCFGDIR=/etc/xinetd.d
[a37e5fc4]167        elif [ -f /etc/redhat-release ]; then
[884b6ce]168                # Distribución basada en paquetes rpm.
[5ee13ae]169                DEPENDENCIES=( curl rsync btrfs-progs procps-ng arp-scan gettext moreutils jq net-tools udpcast libev-devel jansson-devel openssl-devel shim-x64 grub2-efi-x64 grub2-efi-x64-modules gawk libdbi-devel libdbi libdbi-dbd-mysql automake)
[ec536c6]170                # Repositorios para PHP 7 en CentOS.
171                [ "$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]172                INSTALLPKGS="yum install -y"
[a37e5fc4]173                DELETEPKGS="yum remove -y"
[db9e706]174                CHECKPKG="rpm -q --quiet \$package"
[4b96166]175                if which systemctl &>/dev/null; then
[a37e5fc4]176                        STARTSERVICE="eval systemctl restart \$service.service"
[dde65c7]177                        STOPSERVICE="eval systemctl stop \$service.service"
[4b96166]178                        ENABLESERVICE="eval systemctl enable \$service.service"
[a37e5fc4]179                        SERVICESTATUS="eval systemctl status \$service.service"
[4b96166]180                else
[a37e5fc4]181                        STARTSERVICE="eval service \$service restart"
[dde65c7]182                        STOPSERVICE="eval service \$service stop"
[4b96166]183                        ENABLESERVICE="eval chkconfig \$service on"
[a37e5fc4]184                        SERVICESTATUS="eval service \$service status"
[4b96166]185                fi
[2a5c1a4]186                APACHEUSER="apache"
187                APACHEGROUP="apache"
[3b0436d]188                MYSQLCFGDIR=/etc/my.cnf.d
189                MYSQLSERV="mariadb"
[ec536c6]190                PHPFPMSERV="php-fpm"
[65baf16]191                INETDCFGDIR=/etc/xinetd.d
[a37e5fc4]192        else
193                # Otras distribuciones.
194                :
195        fi
196        for service in apache2 httpd; do
[5050850]197                [ -d "/etc/$service" ] && APACHECFGDIR="/etc/$service"
[a37e5fc4]198                if $SERVICESTATUS &>/dev/null; then APACHESERV="$service"; fi
199        done
200        for service in dhcpd dhcpd3-server isc-dhcp-server; do
201                if $SERVICESTATUS &>/dev/null; then DHCPSERV="$service"; fi
202        done
[db9e706]203}
204
205
[fd45e9a]206# Choose an available version to update.
207function chooseVersion()
208{
[d42d7c7]209    local RELEASES DOWNLOADS INSTVERSION INSTRELEASE RELDATE
[fd45e9a]210
211    # Development branch.
212    BRANCH="master"
213    API_URL="https://api.github.com/repos/opengnsys/OpenGnsys/branches/$BRANCH"
[66432fb]214
215    RELEASES=( )
216    DOWNLOADS=( )
[fd45e9a]217    # If updating from a local or very old version, use the default data.
[363defe]218    if [ $REMOTE -eq 1 ] && which jq &>/dev/null && [ -f $INSTALL_TARGET/doc/VERSION.json -o -f $INSTALL_TARGET/doc/VERSION.txt ]; then
[fd45e9a]219        # Installed release.
[363defe]220        [ -f $INSTALL_TARGET/doc/VERSION.json ] && read -pe INSTVERSION INSTRELEASE <<< $(jq -r '.version+" "+.release' $INSTALL_TARGET/doc/VERSION.json)
221        [ -f $INSTALL_TARGET/doc/VERSION.txt ] && read -pe INSTVERSION INSTRELEASE <<< $(awk '{print $2,$3}' $INSTALL_TARGET/doc/VERSION.txt)
[fd45e9a]222        # Fetch tags (releases) data from GitHub.
223        while read -pe TAG URL; do
224            if [[ $TAG =~ ^opengnsys- ]]; then
[d42d7c7]225                [ "${TAG#opengnsys-}" \< "${INSTVERSION%pre}" ] && continue
226                RELDATE=$(curl -s "$URL" | jq -r '.commit.committer.date | split("-") | join("")[:8]')
227                RELEASES+=( "${TAG} ($RELDATE)" )
228                DOWNLOADS+=( "$URL" )
[fd45e9a]229            fi
230        done <<< $(curl -s "$API_URL/../../tags" | jq -r '.[] | .name+" "+.commit.url')
[66432fb]231        # Add development (master) branch.
232        RELEASES+=( "$BRANCH" )
233        DOWNLOADS+=( "$API_URL" )
[fd45e9a]234        # Show selection menu, if needed.
[ecdb637]235        if [ ${#RELEASES[@]} -gt 1 ]; then
[fd45e9a]236            echo "Installed version: $INSTVERSION $INSTRELEASE"
[66432fb]237            echo "Versions available for update (\"$BRANCH\" is the latest development branch):"
[d42d7c7]238            PS3="Enter a number (CTRL-C to exit): "
[fd45e9a]239            select opt in "${RELEASES[@]}"; do
240                if [ -n "$opt" ]; then
[d42d7c7]241                    BRANCH="${opt%% *}"
[fd45e9a]242                    API_URL="${DOWNLOADS[REPLY-1]}"
243                    break
244                fi
245            done
246        fi
247    fi
248    # Download URLs.
249    CODE_URL="https://codeload.github.com/opengnsys/OpenGnsys/zip/$BRANCH"
250    RAW_URL="https://raw.githubusercontent.com/opengnsys/OpenGnsys/$BRANCH"
251}
252
253
[64dd765]254# Comprobar auto-actualización.
255function checkAutoUpdate()
256{
257        local update=0
258
259        # Actaulizar el script si ha cambiado o no existe el original.
[884b6ce]260        if [ $REMOTE -eq 1 ]; then
261                curl -s $RAW_URL/installer/$PROGRAMNAME -o $PROGRAMNAME
[a3a1ff2]262                chmod +x $PROGRAMNAME
[d372e6e]263                if ! diff -q $PROGRAMNAME $INSTALL_TARGET/lib/$PROGRAMNAME 2>/dev/null || ! test -f $INSTALL_TARGET/lib/$PROGRAMNAME; then
[64dd765]264                        mv $PROGRAMNAME $INSTALL_TARGET/lib
265                        update=1
266                else
267                        rm -f $PROGRAMNAME
268                fi
269        else
[d372e6e]270                if ! diff -q $PROGRAMDIR/$PROGRAMNAME $INSTALL_TARGET/lib/$PROGRAMNAME 2>/dev/null || ! test -f $INSTALL_TARGET/lib/$PROGRAMNAME; then
[64dd765]271                        cp -a $PROGRAMDIR/$PROGRAMNAME $INSTALL_TARGET/lib
272                        update=1
273                fi
274        fi
275
276        return $update
277}
278
279
[a0867b37]280function getDateTime()
281{
[5eb61a6]282        date "+%Y%m%d-%H%M%S"
[a0867b37]283}
284
285# Escribe a fichero y muestra por pantalla
286function echoAndLog()
287{
[a3a1ff2]288        echo "$1"
[6ef01d9]289        DATETIME=`getDateTime`
290        echo "$DATETIME;$SSH_CLIENT;$1" >> $LOG_FILE
[a0867b37]291}
292
293function errorAndLog()
294{
[5eb61a6]295        echo "ERROR: $1"
296        DATETIME=`getDateTime`
[6ef01d9]297        echo "$DATETIME;$SSH_CLIENT;ERROR: $1" >> $LOG_FILE
[a0867b37]298}
299
[cd86637]300# Escribe a fichero y muestra mensaje de aviso
301function warningAndLog()
302{
303        local DATETIME=`getDateTime`
304        echo "Warning: $1"
305        echo "$DATETIME;$SSH_CLIENT;Warning: $1" >> $LOG_FILE
306}
307
[a0867b37]308
309#####################################################################
310####### Funciones de copia de seguridad y restauración de ficheros
311#####################################################################
312
313# Hace un backup del fichero pasado por parámetro
314# deja un -last y uno para el día
315function backupFile()
316{
317        if [ $# -ne 1 ]; then
318                errorAndLog "${FUNCNAME}(): invalid number of parameters"
319                exit 1
320        fi
321
322        local fichero=$1
323        local fecha=`date +%Y%m%d`
324
325        if [ ! -f $fichero ]; then
[cd86637]326                warningAndLog "${FUNCNAME}(): file $fichero doesn't exists"
[a0867b37]327                return 1
328        fi
329
[ebbbfc01]330        echoAndLog "${FUNCNAME}(): Making $fichero back-up"
[a0867b37]331
332        # realiza una copia de la última configuración como last
[6ef01d9]333        cp -a $fichero "${fichero}-LAST"
[a0867b37]334
335        # si para el día no hay backup lo hace, sino no
336        if [ ! -f "${fichero}-${fecha}" ]; then
[6ef01d9]337                cp -a $fichero "${fichero}-${fecha}"
[a0867b37]338        fi
339}
340
341# Restaura un fichero desde su copia de seguridad
342function restoreFile()
343{
344        if [ $# -ne 1 ]; then
345                errorAndLog "${FUNCNAME}(): invalid number of parameters"
346                exit 1
347        fi
348
349        local fichero=$1
350
[ebbbfc01]351        echoAndLog "${FUNCNAME}(): restoring file $fichero"
[a0867b37]352        if [ -f "${fichero}-LAST" ]; then
[6ef01d9]353                cp -a "$fichero-LAST" "$fichero"
[a0867b37]354        fi
355}
356
357
358#####################################################################
[295b4ab]359####### Funciones de acceso a base de datos
360#####################################################################
361
362# Actualizar la base datos
363function importSqlFile()
364{
365        if [ $# -ne 4 ]; then
366                errorAndLog "${FNCNAME}(): invalid number of parameters"
367                exit 1
368        fi
369
370        local dbuser="$1"
371        local dbpassword="$2"
372        local database="$3"
373        local sqlfile="$4"
374        local tmpfile=$(mktemp)
[632bd45]375        local mycnf=/tmp/.my.cnf.$$
[295b4ab]376        local status
377
378        if [ ! -r $sqlfile ]; then
379                errorAndLog "${FUNCNAME}(): Unable to read $sqlfile!!"
380                return 1
381        fi
382
383        echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..."
384        chmod 600 $tmpfile
385        sed -e "s/SERVERIP/$SERVERIP/g" -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
[dde2db1]386            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" $sqlfile > $tmpfile
[632bd45]387        # Componer fichero con credenciales de conexión. 
388        touch $mycnf
389        chmod 600 $mycnf
390        cat << EOT > $mycnf
[c073224]391[client]
[09bf701]392user=$dbuser
393password=$dbpassword
[632bd45]394EOT
[785085b]395        # Antes de actualizar, reasignar valores para campos no nulos con nulo por defecto.
396        mysql --defaults-extra-file=$MYCNF -D "$database" -e \
397                "$(mysql --defaults-extra-file=$MYCNF -Nse "
398SELECT CASE WHEN DATA_TYPE LIKE '%int' THEN
399                 CONCAT_WS(' ', 'ALTER TABLE', TABLE_NAME, 'ALTER', COLUMN_NAME, 'SET DEFAULT 0;')
400            WHEN DATA_TYPE LIKE '%char' THEN
401                 CONCAT_WS(' ', 'ALTER TABLE', TABLE_NAME, 'ALTER', COLUMN_NAME, 'SET DEFAULT \'\';')
402            WHEN DATA_TYPE = 'text' THEN
403                 CONCAT_WS(' ', 'ALTER TABLE', TABLE_NAME, 'MODIFY', COLUMN_NAME, 'TEXT NOT NULL;')
404            ELSE ''
405       END
406  FROM information_schema.COLUMNS
407 WHERE TABLE_SCHEMA='$database'
408   AND IS_NULLABLE='NO'
409   AND COLUMN_DEFAULT IS NULL
410   AND COLUMN_KEY='';")"
[632bd45]411        # Ejecutar actualización y borrar fichero de credenciales.
[09bf701]412        mysql --defaults-extra-file=$mycnf --default-character-set=utf8 -D "$database" < $tmpfile
[295b4ab]413        status=$?
[632bd45]414        rm -f $mycnf $tmpfile
[295b4ab]415        if [ $status -ne 0 ]; then
416                errorAndLog "${FUNCNAME}(): error importing $sqlfile in database $database"
417                return 1
418        fi
419        echoAndLog "${FUNCNAME}(): file imported to database $database"
420        return 0
421}
422
[21372e8]423# Comprobar configuración de MySQL y recomendar cambios necesarios.
424function checkMysqlConfig()
425{
[0304465]426        echoAndLog "${FUNCNAME}(): checking MySQL configuration"
[3b0436d]427
428        cp -a $WORKDIR/opengnsys/server/etc/mysqld-og.cnf $MYSQLCFGDIR 2>/dev/null
429        service=$MYSQLSERV; $STARTSERVICE
[21372e8]430
431        echoAndLog "${FUNCNAME}(): MySQL configuration has checked"
432        return 0
433}
[295b4ab]434
435#####################################################################
[a0867b37]436####### Funciones de instalación de paquetes
437#####################################################################
438
439# Instalar las deependencias necesarias para el actualizador.
[64dd765]440function installDependencies()
[a0867b37]441{
[db9e706]442        local package
443
[a37e5fc4]444        # Comprobar si hay que actualizar PHP 5 a PHP 7.
445        eval $UPDATEPKGLIST
446        if [ -f /etc/debian_version ]; then
447                # Basado en paquetes Deb.
[1f0d1d5]448                PHP7VERSION="php7.2"
[ec536c6]449                PHPFPMSERV="${PHP7VERSION}-fpm"
450                PHP5PKGS=( $(dpkg -l | awk '$2~/^php5/ {print $2}') )
[a37e5fc4]451                if [ -n "$PHP5PKGS" ]; then
452                        $DELETEPKGS ${PHP5PKGS[@]}
[ec536c6]453                        PHP5PKGS[0]="$PHP7VERSION"
[a37e5fc4]454                        INSTALLDEPS=${PHP5PKGS[@]//php5*-/${PHP7VERSION}-}
455                fi
456        fi
[ec536c6]457        if [ "$OSDISTRIB" == "centos" ]; then
458                PHP7VERSION=$(yum list -q php7\* 2>/dev/null | awk -F. '/^php/ {print $1; exit;}')
[97b6579]459                PHPFPMSERV="${PHP7VERSION}-${PHPFPMSERV}"
[ec536c6]460                PHP5PKGS=( $(yum list installed | awk '$1~/^php/ && $2~/^5\./ {sub(/\..*$/, "", $1); print $1}') )
461                if [ -n "$PHP5PKGS" ]; then
462                        $DELETEPKGS ${PHP5PKGS[@]}
463                        PHP5PKGS[0]="$PHP7VERSION-php"
464                        INSTALLDEPS=${PHP5PKGS[@]//php-/${PHP7VERSION}-php}
465                fi
466        fi
[a37e5fc4]467
[a0867b37]468        if [ $# = 0 ]; then
[0304465]469                echoAndLog "${FUNCNAME}(): no dependencies are needed"
[c1e00e4]470        else
471                while [ $# -gt 0 ]; do
[a37e5fc4]472                        package="${1/php/$PHP7VERSION}"
[b6fd406]473                        eval $CHECKPKG || INSTALLDEPS="$INSTALLDEPS $package"
[c1e00e4]474                        shift
475                done
476                if [ -n "$INSTALLDEPS" ]; then
[db9e706]477                        $INSTALLPKGS $INSTALLDEPS
[c1e00e4]478                        if [ $? -ne 0 ]; then
[0304465]479                                errorAndLog "${FUNCNAME}(): cannot install some dependencies: $INSTALLDEPS"
[c1e00e4]480                                return 1
481                        fi
482                fi
483        fi
[a0867b37]484}
485
486
487#####################################################################
[884b6ce]488####### Funciones para descargar código
[a0867b37]489#####################################################################
490
[884b6ce]491function downloadCode()
[a0867b37]492{
493        if [ $# -ne 1 ]; then
494                errorAndLog "${FUNCNAME}(): invalid number of parameters"
495                exit 1
496        fi
497
[27dc5ff]498        local url="$1"
[a0867b37]499
[884b6ce]500        echoAndLog "${FUNCNAME}(): downloading code..."
[a0867b37]501
[4f64fa1]502        curl "$url" -o opengnsys.zip && \
503                unzip -qo opengnsys.zip && \
504                rm -fr opengnsys && \
505                mv "OpenGnsys-$BRANCH" opengnsys
[a0867b37]506        if [ $? -ne 0 ]; then
507                errorAndLog "${FUNCNAME}(): error getting code from ${url}, verify your user and password"
508                return 1
509        fi
[884b6ce]510        rm -f opengnsys.zip
511        echoAndLog "${FUNCNAME}(): code was downloaded"
[a0867b37]512        return 0
513}
514
515
516############################################################
517###  Detectar red
518############################################################
519
[07c3a59]520# Comprobar si existe conexión.
521function checkNetworkConnection()
522{
[a0081b7]523        OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"opengnsys.es"}
[884b6ce]524        if which curl &>/dev/null; then
[506c670]525                curl --connect-timeout 10 -s "https://$OPENGNSYS_SERVER" -o /dev/null && \
526                        curl --connect-timeout 10 -s "http://$OPENGNSYS_SERVER" -o /dev/null
[884b6ce]527        elif which wget &>/dev/null; then
[506c670]528                wget --spider -q "https://$OPENGNSYS_SERVER" && \
529                        wget --spider -q "http://$OPENGNSYS_SERVER"
[884b6ce]530        else
531                echoAndLog "${FUNCNAME}(): Cannot execute \"wget\" nor \"curl\"."
532                return 1
533        fi
[07c3a59]534}
535
[0304465]536# Comprobar si la versión es anterior a la actual.
537function checkVersion()
538{
539        local PRE
540
541        # Obtener versión actual y versión a actualizar.
[9815cac]542        [ -f $INSTALL_TARGET/doc/VERSION.txt ] && OLDVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt 2>/dev/null)
543        [ -f $INSTALL_TARGET/doc/VERSION.json ] && OLDVERSION=$(jq -r '.version' $INSTALL_TARGET/doc/VERSION.json 2>/dev/null)
[884b6ce]544        if [ $REMOTE -eq 1 ]; then
[9815cac]545                NEWVERSION=$(curl -s $RAW_URL/doc/VERSION.json 2>/dev/null | jq -r '.version')
[0304465]546        else
[5f0c2dd]547                NEWVERSION=$(jq -r '.version' $PROGRAMDIR/../doc/VERSION.json 2>/dev/null)
[0304465]548        fi
549        [[ "$NEWVERSION" =~ pre ]] && PRE=1
550
551        # Comparar versiones.
552        [[ "$NEWVERSION" < "${OLDVERSION/pre/}" ]] && return 1
553        [ "${NEWVERSION/pre/}" == "$OLDVERSION" -a "$PRE" == "1" ] && return 1
554
555        return 0
556}
557
[739fb00]558# Obtener los parámetros de red del servidor.
559function getNetworkSettings()
560{
561        # Variables globales definidas:
562        # - SERVERIP:   IP local de la interfaz por defecto.
563
564        local DEVICES
565        local dev
566
[90b507d]567        SERVERIP="$ServidorAdm"
[739fb00]568        DEVICES="$(ip -o link show up | awk '!/loopback/ {sub(/:.*/,"",$2); print $2}')"
569        for dev in $DEVICES; do
[2c1b0cf]570                [ -z "$SERVERIP" ] && SERVERIP=$(ip -o addr show dev $dev | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4); exit;}')
[739fb00]571        done
572}
573
[a0867b37]574
575#####################################################################
576####### Funciones específicas de la instalación de Opengnsys
577#####################################################################
578
[5f21d34]579# Actualizar cliente OpenGnsys.
[295b4ab]580function updateClientFiles()
[45f1fe8]581{
[74cd321]582        local ENGINECFG=$INSTALL_TARGET/client/etc/engine.cfg
583
[a43e90d]584        # Actualizar ficheros del cliente.
[74cd321]585        backupFile $ENGINECFG
[0304465]586        echoAndLog "${FUNCNAME}(): Updating OpenGnsys Client files"
[884b6ce]587        rsync -irplt $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
[45f1fe8]588        if [ $? -ne 0 ]; then
589                errorAndLog "${FUNCNAME}(): error while updating client structure"
[51b179a]590                exit 1
[45f1fe8]591        fi
[a43e90d]592
593        # Actualizar librerías del motor de clonación.
[0304465]594        echoAndLog "${FUNCNAME}(): Updating OpenGnsys Cloning Engine files"
[884b6ce]595        rsync -irplt $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
[45f1fe8]596        if [ $? -ne 0 ]; then
597                errorAndLog "${FUNCNAME}(): error while updating engine files"
[51b179a]598                exit 1
[45f1fe8]599        fi
[a3855dc]600        # Actualizar fichero de configuración del motor de clonación.
[c40710e]601        if ! grep -q "^TZ" $ENGINECFG; then
[a3855dc]602                TZ=$(timedatectl status | awk -F"[:()]" '/Time.*zone/ {print $2}')
[c40710e]603                cat << EOT >> $ENGINECFG
[a3855dc]604# OpenGnsys Server timezone.
605TZ="${TZ// /}"
606EOT
607        fi
[8fc7ce1]608        if ! diff -q ${ENGINECFG}{,-LAST} &>/dev/null; then
[c40710e]609                NEWFILES="$NEWFILES $ENGINECFG"
610        else
611                rm -f ${ENGINECFG}-LAST
612        fi
[ec045b1]613        # Obtener URL para descargas adicionales.
614        DOWNLOADURL=$(oglivecli config download-url 2>/dev/null)
[a0081b7]615        DOWNLOADURL=${DOWNLOADURL:-"https://$OPENGNSYS_SERVER/trac/downloads"}
[a3855dc]616
[0304465]617        echoAndLog "${FUNCNAME}(): client files successfully updated"
[45f1fe8]618}
[4e51cb0]619
[5050850]620# Crear certificado para la firma de cargadores de arranque, si es necesario.
621function createCerts ()
622{
623        local SSLCFGDIR=$INSTALL_TARGET/client/etc/ssl
624        mkdir -p $SSLCFGDIR/{certs,private}
625        if [ ! -f $SSLCFGDIR/private/opengnsys.key ]; then
626                echoAndLog "${FUNCNAME}(): creating certificate files"
627                openssl req -new -x509 -newkey rsa:2048 -keyout $SSLCFGDIR/private/opengnsys.key -out $SSLCFGDIR/certs/opengnsys.crt -nodes -days 3650 -subj "/CN=OpenGnsys/"
628                openssl x509 -in $SSLCFGDIR/certs/opengnsys.crt -out $SSLCFGDIR/certs/opengnsys.cer -outform DER
629                echoAndLog "${FUNCNAME}(): certificate successfully created"
630        fi
631}
632
[3ce53a7]633# Configurar HTTPS y exportar usuario y grupo del servicio Apache.
634function apacheConfiguration ()
[4e51cb0]635{
[9215580]636        local config template module socketfile
[6f4d39b]637
[ec536c6]638        # Avtivar PHP-FPM.
639        echoAndLog "${FUNCNAME}(): configuring PHP-FPM"
640        service=$PHPFPMSERV
641        $ENABLESERVICE; $STARTSERVICE
642
[9215580]643        # Activar módulos de Apache.
[2e38f60]644        if [ -e $APACHECFGDIR/sites-available/opengnsys.conf ]; then
[0304465]645                echoAndLog "${FUNCNAME}(): Configuring Apache modules"
[3ce53a7]646                a2ensite default-ssl
[9215580]647                for module in $APACHEENABLEMODS; do a2enmod -q "$module"; done
648                for module in $APACHEDISABLEMODS; do a2dismod -q "${module//PHP7VERSION}"; done
[3ce53a7]649                a2ensite opengnsys
[5f21d34]650        elif [ -e $APACHECFGDIR/conf.modules.d ]; then
[0304465]651                echoAndLog "${FUNCNAME}(): Configuring Apache modules"
[5f21d34]652                sed -i '/rewrite/s/^#//' $APACHECFGDIR/*.conf
[3ce53a7]653        fi
[ec536c6]654        # Elegir plantilla según versión de Apache.
655        if [ -n "$(apachectl -v | grep "2\.[0-2]")" ]; then
656               template=$WORKDIR/opengnsys/server/etc/apache-prev2.4.conf.tmpl > $config
657        else
658               template=$WORKDIR/opengnsys/server/etc/apache.conf.tmpl
659        fi
[ea016a46]660        sockfile=$(find /run/php -name "php*.sock" -type s -print 2>/dev/null | tail -1)
[6f4d39b]661        # Actualizar configuración de Apache a partir de fichero de plantilla.
662        for config in $APACHECFGDIR/{,sites-available/}opengnsys.conf; do
[37481d8]663                if [ -e $config ]; then
664                        if [ -n "$sockfile" ]; then
665                                sed -e "s,CONSOLEDIR,$INSTALL_TARGET/www,g; s,proxy:fcgi:.*,proxy:unix:${sockfile%% *}|fcgi://localhost\",g" $template > $config
666                        else
667                                sed -e "s,CONSOLEDIR,$INSTALL_TARGET/www,g" $template > $config
668                        fi
669                fi
[900be258]670        done
671
672        # Reiniciar Apache.
[ec536c6]673        service=$APACHESERV; $STARTSERVICE
[900be258]674
[3ce53a7]675        # Variables de ejecución de Apache.
[4e51cb0]676        # - APACHE_RUN_USER
677        # - APACHE_RUN_GROUP
[2e38f60]678        if [ -f $APACHECFGDIR/envvars ]; then
679                source $APACHECFGDIR/envvars
[4e51cb0]680        fi
[2e38f60]681        APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
[de8bbb1]682        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
[4e51cb0]683}
684
[4b96166]685# Configurar servicio Rsync.
686function rsyncConfigure()
687{
688        local service
689
690        # Configurar acceso a Rsync.
691        if [ ! -f /etc/rsyncd.conf ]; then
[0304465]692                echoAndLog "${FUNCNAME}(): Configuring Rsync service"
[65baf16]693                NEWFILES="$NEWFILES /etc/rsyncd.conf"
[4b96166]694                sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENTUSER/g" \
695                    $WORKDIR/opengnsys/repoman/etc/rsyncd.conf.tmpl > /etc/rsyncd.conf
696                # Habilitar Rsync.
697                if [ -f /etc/default/rsync ]; then
698                        perl -pi -e 's/RSYNC_ENABLE=.*/RSYNC_ENABLE=inetd/' /etc/default/rsync
699                fi
700                if [ -f $INETDCFGDIR/rsync ]; then
701                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/rsync
702                else
703                        cat << EOT > $INETDCFGDIR/rsync
704service rsync
705{
706        disable = no
707        socket_type = stream
708        wait = no
709        user = root
710        server = $(which rsync)
711        server_args = --daemon
712        log_on_failure += USERID
713        flags = IPv6
714}
715EOT
716                fi
717                # Activar e iniciar Rsync.
718                service="rsync"  $ENABLESERVICE
[ab7f563]719                service="xinetd"
720                $ENABLESERVICE; $STARTSERVICE
[4b96166]721        fi
722}
723
[5f21d34]724# Copiar ficheros del OpenGnsys Web Console.
[a0867b37]725function updateWebFiles()
726{
[2b793a8]727        local ERRCODE COMPATDIR f
728
[a0867b37]729        echoAndLog "${FUNCNAME}(): Updating web files..."
[2b793a8]730
731        # Copiar los ficheros nuevos conservando el archivo de configuración de acceso.
732        backupFile $INSTALL_TARGET/www/controlacceso.php
733        mv $INSTALL_TARGET/www $INSTALL_TARGET/WebConsole
[884b6ce]734        rsync -irplt $WORKDIR/opengnsys/admin/WebConsole $INSTALL_TARGET
[2b793a8]735        ERRCODE=$?
736        mv $INSTALL_TARGET/WebConsole $INSTALL_TARGET/www
[1635f45]737        rm -fr $INSTALL_TARGET/www/xajax
[900be258]738        unzip -o $WORKDIR/opengnsys/admin/slim-2.6.1.zip -d $INSTALL_TARGET/www/rest
[8b8e948]739        unzip -o $WORKDIR/opengnsys/admin/swagger-ui-2.2.5.zip -d $INSTALL_TARGET/www/rest
[d655cc4]740        if [ $ERRCODE != 0 ]; then
[a0867b37]741                errorAndLog "${FUNCNAME}(): Error updating web files."
742                exit 1
743        fi
[2b793a8]744        restoreFile $INSTALL_TARGET/www/controlacceso.php
745
[1a2fa9d8]746        # Cambiar acceso a protocolo HTTPS.
747        if grep -q "http://" $INSTALL_TARGET/www/controlacceso.php 2>/dev/null; then
748                echoAndLog "${FUNCNAME}(): updating web access file"
749                perl -pi -e 's!http://!https://!g' $INSTALL_TARGET/www/controlacceso.php
750                NEWFILES="$NEWFILES $INSTALL_TARGET/www/controlacceso.php"
751        fi
752
[2b793a8]753        # Compatibilidad con dispositivos móviles.
754        COMPATDIR="$INSTALL_TARGET/www/principal"
755        for f in acciones administracion aula aulas hardwares imagenes menus repositorios softwares; do
756                sed 's/clickcontextualnodo/clicksupnodo/g' $COMPATDIR/$f.php > $COMPATDIR/$f.device.php
757        done
[d70a45f]758        cp -a $COMPATDIR/imagenes.device.php $COMPATDIR/imagenes.device4.php
[aafe8f9]759        # Acceso al manual de usuario
760        ln -fs ../doc/userManual $INSTALL_TARGET/www/userManual
[0645906]761        # Fichero de log de la API REST.
762        touch $INSTALL_TARGET/log/{ogagent,rest,remotepc}.log
[2b793a8]763
[0304465]764        echoAndLog "${FUNCNAME}(): Web files successfully updated"
[a0867b37]765}
766
[ec045b1]767# Copiar ficheros en la zona de descargas de OpenGnsys Web Console.
768function updateDownloadableFiles()
769{
[1de0d12d]770        local VERSIONFILE OGVERSION FILENAME TARGETFILE
771
772        # Obtener versión a descargar.
773        VERSIONFILE="$INSTALL_TARGET/doc/VERSION.json"
774        OGVERSION="$(jq -r ".ogagent // \"$NEWVERSION\"" $VERSIONFILE 2>/dev/null || echo "$NEWVERSION")"
775        FILENAME="ogagentpkgs-$OGVERSION.tar.gz"
776        TARGETFILE=$WORKDIR/$FILENAME
[ec045b1]777
778        # Descargar archivo comprimido, si es necesario.
779        if [ -s $PROGRAMDIR/$FILENAME ]; then
780                echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
781                mv $PROGRAMDIR/$FILENAME $TARGETFILE
782        else
783                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
[884b6ce]784                curl $DOWNLOADURL/$FILENAME -o $TARGETFILE
[ec045b1]785        fi
786        if [ ! -s $TARGETFILE ]; then
787                errorAndLog "${FUNCNAME}(): Cannot download $FILENAME"
788                return 1
789        fi
790
791        # Descomprimir fichero en zona de descargas.
792        tar xvzf $TARGETFILE -C $INSTALL_TARGET/www/descargas
793        if [ $? != 0 ]; then
[0304465]794                errorAndLog "${FUNCNAME}(): Error uncompressing archive $FILENAME"
[884b6ce]795                return 1
[ec045b1]796        fi
797}
798
[72134d5]799# Copiar carpeta de Interface
[64dd765]800function updateInterfaceAdm()
[72134d5]801{
[27dc5ff]802        local errcode=0
[2b793a8]803
[72134d5]804        # Crear carpeta y copiar Interface
805        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
806        mv $INSTALL_TARGET/client/interfaceAdm $INSTALL_TARGET/client/Interface
[884b6ce]807        rsync -irplt $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client
[27dc5ff]808        errcoce=$?
[72134d5]809        mv $INSTALL_TARGET/client/Interface $INSTALL_TARGET/client/interfaceAdm
[27dc5ff]810        if [ $errcode -ne 0 ]; then
[72134d5]811                echoAndLog "${FUNCNAME}(): error while updating admin interface"
812                exit 1
813        fi
[0304465]814        echoAndLog "${FUNCNAME}(): Admin interface successfully updated"
[72134d5]815}
[a0867b37]816
[5d6bf97]817# Crear documentación Doxygen para la consola web.
818function makeDoxygenFiles()
819{
820        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
821        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
822                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
823        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
[0304465]824                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files"
[5d6bf97]825                return 1
826        fi
[45f1fe8]827        rm -fr "$INSTALL_TARGET/www/api"
[15b2a4e]828        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
829        rm -fr $INSTALL_TARGET/www/{man,perlmod,rtf}
[0304465]830        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully"
[5d6bf97]831}
832
833
[a0867b37]834# Crea la estructura base de la instalación de opengnsys
835function createDirs()
836{
[eb9424f]837        # Crear estructura de directorios.
[a0867b37]838        echoAndLog "${FUNCNAME}(): creating directory paths in ${INSTALL_TARGET}"
[8cb279b]839        local dir MKNETDIR
[7bb72f7]840
[cfad47b]841        mkdir -p ${INSTALL_TARGET}/{bin,doc,etc,lib,sbin,www}
[d7ece95]842        mkdir -p ${INSTALL_TARGET}/{client,images/groups}
[a0867b37]843        mkdir -p ${INSTALL_TARGET}/log/clients
[eb9424f]844        ln -fs ${INSTALL_TARGET}/log /var/log/opengnsys
[7bb72f7]845        # Detectar directorio de instalación de TFTP.
846        if [ ! -L ${INSTALL_TARGET}/tftpboot ]; then
847                for dir in /var/lib/tftpboot /srv/tftp; do
848                        [ -d $dir ] && ln -fs $dir ${INSTALL_TARGET}/tftpboot
849                done
850        fi
[b4d8d51]851        mkdir -p $INSTALL_TARGET/tftpboot/{menu.lst,grub}/examples
[a0867b37]852        if [ $? -ne 0 ]; then
853                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
854                return 1
855        fi
[663cd905]856        ! [ -f $INSTALL_TARGET/tftpboot/menu.lst/templates/00unknown ] && mv $INSTALL_TARGET/tftpboot/menu.lst/templates/* $INSTALL_TARGET/tftpboot/menu.lst/examples
[b4d8d51]857        ! [ -f $INSTALL_TARGET/tftpboot/grub/templates/10 ] && mv $INSTALL_TARGET/tftpboot/grub/templates/* $INSTALL_TARGET/tftpboot/grub/examples
[a0867b37]858
[8cb279b]859        # Preparar arranque en red con Grub.
860        for f in grub-mknetdir grub2-mknetdir; do
861                if which $f &>/dev/null; then MKNETDIR=$f; fi
862        done
[5969a13]863        $MKNETDIR --net-directory=${INSTALL_TARGET}/tftpboot --subdir=grub
[8cb279b]864
[eb9424f]865        # Crear usuario ficticio.
866        if id -u $OPENGNSYS_CLIENTUSER &>/dev/null; then
867                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENTUSER\" is already created"
868        else
[5f21d34]869                echoAndLog "${FUNCNAME}(): creating OpenGnsys user"
[eb9424f]870                useradd $OPENGNSYS_CLIENTUSER 2>/dev/null
871                if [ $? -ne 0 ]; then
[5f21d34]872                        errorAndLog "${FUNCNAME}(): error creating OpenGnsys user"
[eb9424f]873                        return 1
874                fi
875        fi
876
[57f7e9c]877        # Mover el fichero de registro al directorio de logs.
878        echoAndLog "${FUNCNAME}(): moving update log file"
879        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
[7669bca]880        chmod 600 $LOG_FILE
[57f7e9c]881
[a0867b37]882        echoAndLog "${FUNCNAME}(): directory paths created"
883        return 0
884}
885
[566e84f]886# Actualización incremental de la BD (versión actaul a actaul+1, hasta final-1 a final).
887function updateDatabase()
888{
889        local DBDIR="$WORKDIR/opengnsys/admin/Database"
890        local file FILES=""
891
892        echoAndLog "${FUNCNAME}(): looking for database updates"
893        pushd $DBDIR >/dev/null
894        # Bucle de actualización incremental desde versión actual a la final.
895        for file in $OPENGNSYS_DATABASE-*-*.sql; do
896                case "$file" in
897                        $OPENGNSYS_DATABASE-$OLDVERSION-$NEWVERSION.sql)
898                                # Actualización única de versión inicial y final.
899                                FILES="$FILES $file"
900                                break
901                                ;;
902                        $OPENGNSYS_DATABASE-*-postinst.sql)
903                                # Ignorar fichero específico de post-instalación.
904                                ;;
905                        $OPENGNSYS_DATABASE-$OLDVERSION-*.sql)
906                                # Actualización de versión n a n+1.
907                                FILES="$FILES $file"
[b5db03a]908                                OLDVERSION="$(echo ${file%.*} | cut -f3 -d-)"
[566e84f]909                                ;;
910                        $OPENGNSYS_DATABASE-*-$NEWVERSION.sql)
911                                # Última actualización de versión final-1 a final.
912                                if [ -n "$FILES" ]; then
913                                        FILES="$FILES $file"
914                                        break
915                                fi
916                                ;;
917                esac
918        done
919        # Aplicar posible actualización propia para la versión final.
920        file=$OPENGNSYS_DATABASE-$NEWVERSION.sql
921        if [ -n "$FILES" -o "$OLDVERSION" = "$NEWVERSION" -a -r $file ]; then
922                FILES="$FILES $file"
923        fi
924
925        popd >/dev/null
926        if [ -n "$FILES" ]; then
927                for file in $FILES; do
[0cfe47a]928                        importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $DBDIR/$file
[566e84f]929                done
930                echoAndLog "${FUNCNAME}(): database is update"
931        else
932                echoAndLog "${FUNCNAME}(): database unchanged"
933        fi
934}
935
[a0867b37]936# Copia ficheros de configuración y ejecutables genéricos del servidor.
[64dd765]937function updateServerFiles()
[bb30a50]938{
[c1e00e4]939        # No copiar ficheros del antiguo cliente Initrd
[873cf1e]940        local SOURCES=( repoman/bin \
[c1e00e4]941                        server/bin \
[3e7d77b]942                        server/lib \
[42a0e41]943                        admin/Sources/Services/ogAdmRepoAux \
[873cf1e]944                        server/tftpboot \
[5969a13]945                        /usr/lib/shim/shimx64.efi.signed \
946                        /usr/lib/grub/x86_64-efi-signed/grubnetx64.efi.signed \
[bb30a50]947                        installer/opengnsys_uninstall.sh \
[6777e3e]948                        installer/opengnsys_export.sh \
949                        installer/opengnsys_import.sh \
[873cf1e]950                        doc )
951        local TARGETS=( bin \
952                        bin \
[3e7d77b]953                        lib \
[cdad332]954                        sbin/ogAdmRepoAux \
[873cf1e]955                        tftpboot \
[5969a13]956                        tftpboot/shimx64.efi.signed \
957                        tftpboot/grubx64.efi \
[9a2c0f9d]958                        lib/opengnsys_uninstall.sh \
[6777e3e]959                        lib/opengnsys_export.sh \
960                        lib/opengnsys_import.sh \
[873cf1e]961                        doc )
[a0867b37]962
963        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
964                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
965                exit 1
966        fi
967
968        echoAndLog "${FUNCNAME}(): updating files in server directories"
969        pushd $WORKDIR/opengnsys >/dev/null
970        local i
971        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
[27dc5ff]972                if [ -d "$INSTALL_TARGET/${TARGETS[i]}" ]; then
[884b6ce]973                        rsync -irplt "${SOURCES[i]}" $(dirname $(readlink -e "$INSTALL_TARGET/${TARGETS[i]}"))
[aa36857]974                else
[56f100f]975                        rsync -irplt "${SOURCES[i]}" $(readlink -m "$INSTALL_TARGET/${TARGETS[i]}")
[aa36857]976                fi
[a0867b37]977        done
978        popd >/dev/null
[df3cd7f]979        NEWFILES=""             # Ficheros de configuración que han cambiado de formato.
[f80f839]980        if grep -q 'pxelinux.0' /etc/dhcp*/dhcpd*.conf; then
[df3cd7f]981                echoAndLog "${FUNCNAME}(): updating DHCP files"
[f80f839]982                perl -pi -e 's/pxelinux.0/grldr/' /etc/dhcp*/dhcpd*.conf
[a37e5fc4]983                service=$DHCPSERV; $STARTSERVICE
[df3cd7f]984                NEWFILES="/etc/dhcp*/dhcpd*.conf"
985        fi
[5969a13]986        if ! grep -q 'shimx64.efi.signed' /etc/dhcp*/dhcpd*.conf; then
987                echoAndLog "${FUNCNAME}(): updating DHCP files for UEFI computers"
988                UEFICFG="    # 0007 == x64 EFI boot\n"\
989"    if option arch = 00:07 {\n"\
990"        filename \"shimx64.efi.signed\";\n"\
991"    } else {\n"\
992"        filename \"grldr\";\n"\
993"    }"
[8f24716]994                sed -i -e 1i"option arch code 93 = unsigned integer 16;" -e s@"^.*grldr\"\;"@"$UEFICFG"@g /etc/dhcp*/dhcpd*.conf
[5969a13]995                service=$DHCPSERV; $STARTSERVICE
996                NEWFILES="/etc/dhcp*/dhcpd*.conf"
997        fi
[d372e6e]998        if ! diff -q $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys 2>/dev/null; then
[df3cd7f]999                echoAndLog "${FUNCNAME}(): updating new init file"
1000                backupFile /etc/init.d/opengnsys
[4816ea5]1001                service="opengnsys"
1002                $STOPSERVICE
[df3cd7f]1003                cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
[4816ea5]1004                systemctl daemon-reload
1005                $STARTSERVICE
[df3cd7f]1006                NEWFILES="$NEWFILES /etc/init.d/opengnsys"
1007        fi
[9da3f87]1008        if ! diff -q \
1009             $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.service \
1010             /lib/systemd/system/opengnsys.service 2>/dev/null; then
1011                echoAndLog "${FUNCNAME}(): updating new service file"
1012                backupFile /lib/systemd/system/opengnsys.service
1013                service="opengnsys"
1014                $STOPSERVICE
1015                cp -a \
1016                   $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.service \
1017                   /lib/systemd/system/opengnsys.service
1018                systemctl daemon-reload
1019                $STARTSERVICE
1020                NEWFILES="$NEWFILES /lib/systemd/system/opengnsys.service"
1021        fi
[3b8ef0d]1022        if ! diff -q $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default /etc/default/opengnsys >/dev/null; then
1023                echoAndLog "${FUNCNAME}(): updating new default file"
1024                backupFile /etc/default/opengnsys
1025                # Buscar si hay nuevos parámetros.
1026                local var valor
1027                while IFS="=" read -e var valor; do
1028                        [[ $var =~ ^# ]] || \
1029                                grep -q "^$var=" /etc/default/opengnsys || \
1030                                echo "$var=$valor" >> /etc/default/opengnsys
1031                done < $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default
1032                NEWFILES="$NEWFILES /etc/default/opengnsys"
1033        fi
[a3855dc]1034
[9ee62ad]1035        echoAndLog "${FUNCNAME}(): updating cron files"
[db9e706]1036        [ ! -f /etc/cron.d/torrentcreator ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
1037        [ ! -f /etc/cron.d/torrenttracker ] && echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
[dc762088]1038        [ ! -f /etc/cron.d/imagedelete ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
[0645906]1039        [ ! -f /etc/cron.d/ogagentqueue ] && echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/ogagentqueue.cron ] && $INSTALL_TARGET/bin/ogagentqueue.cron" > /etc/cron.d/ogagentqueue
[b4d8d51]1040
[d9b2413]1041        echoAndLog "${FUNCNAME}(): deleting deprecated cron file"
1042        [ -e /etc/cron.d/opengnsys ] && rm -f /etc/cron.d/opengnsys \
1043                                              $INSTALL_TARGET/bin/opengnsys.cron
1044
[b4d8d51]1045        # Se modifican los nombres de las plantilla PXE por compatibilidad con los equipos UEFI.
1046        if [ -f $INSTALL_TARGET/tftpboot/menu.lst/templates/01 ]; then
1047            BIOSPXEDIR="$INSTALL_TARGET/tftpboot/menu.lst/templates"
1048            mv $BIOSPXEDIR/01 $BIOSPXEDIR/10
[74e6712]1049            sed -i "s/\bMBR\b/1hd/" $BIOSPXEDIR/10
[b4d8d51]1050        fi
[8f24716]1051        echoAndLog "${FUNCNAME}(): server files successfully updated"
[a0867b37]1052}
1053
1054####################################################################
1055### Funciones de compilación de código fuente de servicios
1056####################################################################
1057
[dde65c7]1058# Mueve el fichero del nuevo servicio si es distinto al del directorio destino.
1059function moveNewService()
1060{
1061        local service
1062
1063        # Recibe 2 parámetros: fichero origen y directorio destino.
1064        [ $# == 2 ] || return 1
[ddcb0cf]1065        [ -f  $1 -a -d $2 ] || return 1
[dde65c7]1066
1067        # Comparar los ficheros.
[ddcb0cf]1068        if ! diff -q $1 $2/$(basename $1) &>/dev/null; then
[dde65c7]1069                # Parar los servicios si fuese necesario.
[646ef92]1070                service="opengnsys"
1071                [ -z "$NEWSERVICES" ] && $STOPSERVICE
[dde65c7]1072                # Nuevo servicio.
1073                NEWSERVICES="$NEWSERVICES $(basename $1)"
1074                # Mover el nuevo fichero de servicio
1075                mv $1 $2
[646ef92]1076                $STARTSERVICE
[dde65c7]1077        fi
1078}
1079
1080
[03f813b]1081# Compiling and updating OpenGnsys Server service
[c070d3d]1082function ogServerCompilation()
[a0867b37]1083{
[c070d3d]1084        local ogserverUrl="https://codeload.github.com/opengnsys/ogServer/zip/$BRANCH"
[03f813b]1085        local error=0 serv
[c070d3d]1086
1087        echoAndLog "${FUNCNAME}(): downloading ogServer code..."
1088
1089        if ! (curl "${ogserverUrl}" -o ogserver.zip && \
1090              unzip -qo "ogserver.zip")
1091        then
1092                errorAndLog "${FUNCNAME}(): "\
1093                            "error getting ogServer code from ${ogserverUrl}"
1094                return 1
1095        fi
1096        rm -f ogserver.zip
1097        echoAndLog "${FUNCNAME}(): ogServer code was downloaded"
[bb30a50]1098
[5f21d34]1099        echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Admin Server"
[c070d3d]1100        pushd "$WORKDIR/ogServer-$BRANCH"
[c583144]1101        autoreconf -fi && ./configure && make && moveNewService ogserver $INSTALL_TARGET/sbin
[bb30a50]1102        if [ $? -ne 0 ]; then
[c070d3d]1103                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Server"
1104                error=1
[bb30a50]1105        fi
1106        popd
[03f813b]1107        # Renaming OpenGnsys Server configuration file, if needed
1108        [ -e $INSTALL_TARGET/etc/ogAdmServer.cfg ] && \
[e7ffae8]1109            rm -f $INSTALL_TARGET/etc/ogAdmServer.cfg
1110        [ -e $INSTALL_TARGET/etc/ogserver.cfg ] && \
1111            rm -f $INSTALL_TARGET/etc/ogserver.cfg
1112        if [ ! -e $INSTALL_TARGET/etc/ogserver.json ]; then
1113                echo "{
1114                        \"rest\" : {
1115                                \"ip\" : \"$ServidorAdm\",
1116                                \"port\" : \"8888\",
1117                                \"api_token\": \"$APITOKEN\"
1118                        },
1119                        \"database\" : {
1120                                \"ip\": \"$datasource\",
1121                                \"port\": \"3306\",
1122                                \"name\" : \"$CATALOG\",
1123                                \"user\" : \"$USUARIO\",
1124                                \"pass\" : \"$PASSWORD\"
1125                        },
1126                        \"wol\" : {
1127                                \"interface\" : \"$INTERFACE\"
1128                        }
1129                }" | jq '.' > "$INSTALL_TARGET"/etc/ogserver.json
1130        fi
[03f813b]1131        # Remove old OpenGnsys services
1132        for serv in ogAdmAgent ogAdmRepo ogAdmServer; do
1133                pgrep $serv > /dev/null && pkill -9 $serv && \
1134                    echoAndLog "${FUNCNAME}(): removing deprecated $serv service"
[f1a0909]1135                rm -f $INSTALL_TARGET/sbin/$serv
1136                if [ $serv != ogAdmRepo ]; then
1137                        rm -f $INSTALL_TARGET/etc/$serv.cfg
1138                fi
[03f813b]1139        done
1140        # Generating an ogServer API token, if it does not exist
[e7ffae8]1141        [ -z "$APITOKEN" ] && \
1142            $INSTALL_TARGET/bin/settoken -f
[03f813b]1143        # Updating service file, if needed
[f6e87d3]1144        if ! diff -q \
1145             "$WORKDIR"/ogServer-"$BRANCH"/cfg/ogserver.service \
1146             /lib/systemd/system/ogserver.service 2>/dev/null; then
1147                service="opengnsys"
1148                $STOPSERVICE
1149                echoAndLog "${FUNCNAME}(): updating new service file"
1150                backupFile /lib/systemd/system/ogserver.service
[bbf5371]1151                service="ogserver"
[f6e87d3]1152                $STOPSERVICE
1153                cp -a \
1154                   "$WORKDIR"/ogServer-"$BRANCH"/cfg/ogserver.service \
1155                   /lib/systemd/system/ogserver.service
1156                systemctl daemon-reload
1157                $STARTSERVICE
1158                service="opengnsys"
1159                $STARTSERVICE
1160                NEWFILES="$NEWFILES /lib/systemd/system/ogserver.service"
1161        fi
1162
[c070d3d]1163        return $error
[a0867b37]1164}
1165
1166
1167####################################################################
[5f21d34]1168### Funciones instalacion cliente OpenGnsys
[a0867b37]1169####################################################################
1170
[5f21d34]1171# Actualizar cliente OpenGnsys
[c1e00e4]1172function updateClient()
1173{
[0595bdf]1174        local FILENAME=ogLive-bionic-5.4.0-40-generic-amd64-r20200629.85eceaf.iso       # 1.2 (64 bits)
[0b85cc93]1175        local SOURCEFILE=$DOWNLOADURL/$FILENAME
[0496417]1176        local TARGETFILE=$(oglivecli config download-dir)/$FILENAME
[0b85cc93]1177        local SOURCELENGTH
1178        local TARGETLENGTH
[0496417]1179        local OGINITRD
[a63345ac]1180        local SAMBAPASS
[0b85cc93]1181
[0496417]1182        # Comprobar si debe convertirse el antiguo cliente al nuevo formato ogLive.
1183        if oglivecli check | grep -q "oglivecli convert"; then
1184                echoAndLog "${FUNCNAME}(): Converting OpenGnsys Client to default ogLive"
1185                oglivecli convert
1186        fi
[0b85cc93]1187        # Comprobar si debe actualizarse el cliente.
[5f0c2dd]1188        SOURCELENGTH=$(curl -sI $SOURCEFILE 2>&1 | awk '/Content-Length:/ {gsub("\r", ""); print $2}')
[0496417]1189        TARGETLENGTH=$(stat -c "%s" $TARGETFILE 2>/dev/null)
[d4e90c1]1190        [ -z $TARGETLENGTH ] && TARGETLENGTH=0
[0b85cc93]1191        if [ "$SOURCELENGTH" != "$TARGETLENGTH" ]; then
[ec045b1]1192                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
[0496417]1193                oglivecli download $FILENAME
[0b85cc93]1194                if [ ! -s $TARGETFILE ]; then
[ec045b1]1195                        errorAndLog "${FUNCNAME}(): Error downloading $FILENAME"
[0b85cc93]1196                        return 1
1197                fi
[1893b9d]1198                # Actaulizar la imagen ISO del ogclient.
[0304465]1199                echoAndLog "${FUNCNAME}(): Updatting ogLive client"
[0496417]1200                oglivecli install $FILENAME
[e1c01217]1201               
[2e1b900]1202                INSTALLEDOGLIVE=${FILENAME%.*}
[ee4beb4]1203
[0304465]1204                echoAndLog "${FUNCNAME}(): ogLive successfully updated"
[0b85cc93]1205        else
[65baf16]1206                # Si no existe, crear el fichero de claves de Rsync.
1207                if [ ! -f /etc/rsyncd.secrets ]; then
[ec045b1]1208                        echoAndLog "${FUNCNAME}(): Restoring ogLive access key"
[0496417]1209                        OGINITRD=$(oglivecli config install-dir)/$(jq -r ".oglive[.default].directory")/oginitrd.img
[65baf16]1210                        SAMBAPASS=$(gzip -dc $OGINITRD | \
1211                                    cpio -i --to-stdout scripts/ogfunctions 2>&1 | \
1212                                    grep "^[    ].*OPTIONS=" | \
1213                                    sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
[0496417]1214                        echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | setsmbpass
[65baf16]1215                else
[ec045b1]1216                        echoAndLog "${FUNCNAME}(): ogLive is already updated"
[65baf16]1217                fi
[04e5d96]1218                # Versión del ogLive instalado.
1219                echo "${FILENAME%.*}" > $INSTALL_TARGET/doc/veroglive.txt
[c1e00e4]1220        fi
1221}
[a0867b37]1222
[affce16]1223# Update ogClient
1224function updateOgClient()
1225{
1226        local ogclientUrl="https://codeload.github.com/opengnsys/ogClient/zip/$BRANCH"
[b672456]1227        local CLIENTPASS
[affce16]1228
1229        echoAndLog "${FUNCNAME}(): downloading ogClient code..."
1230
1231        if ! (curl "${ogclientUrl}" -o ogclient.zip && \
1232             unzip -qo ogclient.zip)
1233        then
1234                errorAndLog "${FUNCNAME}(): "\
1235                            "error getting ogClient code from ${ogclientUrl}"
1236                return 1
1237        fi
1238        if [ -e $INSTALL_TARGET/client/ogClient/cfg/ogclient.json ]; then
1239             rm -f ogClient-"$BRANCH"/cfg/ogclient.json
[b672456]1240        else
1241             CLIENTPASS=$(awk -F":" '{print $2}' /etc/rsyncd.secrets)
1242             sed -i -e 's/127.0.0.1/'$ServidorAdm'/' \
1243                -e 's/pass'.*$'/pass\": "'$CLIENTPASS'"/' \
1244                ogClient-"$BRANCH"/cfg/ogclient.json
[affce16]1245        fi
[64e2155]1246        rsync -irplt "ogClient-$BRANCH/" $INSTALL_TARGET/client/ogClient
[affce16]1247        rm -f ogclient.zip
1248        echoAndLog "${FUNCNAME}(): ogClient code was downloaded and updated"
1249
1250        return 0
1251}
1252
[5b95ab6]1253# Comprobar permisos y ficheros.
1254function checkFiles()
1255{
[fbc7333]1256        local LOGROTATEDIR=/etc/logrotate.d
1257
[5b95ab6]1258        # Comprobar permisos adecuados.
1259        if [ -x $INSTALL_TARGET/bin/checkperms ]; then
[0304465]1260                echoAndLog "${FUNCNAME}(): Checking permissions"
[5b95ab6]1261                OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENTUSER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" $INSTALL_TARGET/bin/checkperms
1262        fi
1263        # Eliminamos el fichero de estado del tracker porque es incompatible entre los distintos paquetes
1264        if [ -f /tmp/dstate ]; then
[0304465]1265                echoAndLog "${FUNCNAME}(): Deleting unused files"
[5b95ab6]1266                rm -f /tmp/dstate
1267        fi
[59d6670]1268        # Crear nuevos ficheros de logrotate y borrar el fichero antiguo.
[fbc7333]1269        if [ -d $LOGROTATEDIR ]; then
[59d6670]1270                rm -f $LOGROTATEDIR/opengnsys
[fbc7333]1271                if [ ! -f $LOGROTATEDIR/opengnsysServer ]; then
1272                        echoAndLog "${FUNCNAME}(): Creating logrotate configuration file for server"
1273                        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1274                                $WORKDIR/opengnsys/server/etc/logrotate.tmpl > $LOGROTATEDIR/opengnsysServer
1275                fi
1276                if [ ! -f $LOGROTATEDIR/opengnsysRepo ]; then
1277                        echoAndLog "${FUNCNAME}(): Creating logrotate configuration file for repository"
1278                        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1279                                $WORKDIR/opengnsys/server/etc/logrotate.tmpl > $LOGROTATEDIR/opengnsysRepo
1280                fi
1281        fi
[5b95ab6]1282}
1283
[eb9424f]1284# Resumen de actualización.
1285function updateSummary()
1286{
1287        # Actualizar fichero de versión y revisión.
[884b6ce]1288        local VERSIONFILE REVISION
[3bbaf79]1289        VERSIONFILE="$INSTALL_TARGET/doc/VERSION.json"
[5f0c2dd]1290        # Obtener revisión.
1291        if [ $REMOTE -eq 1 ]; then
1292                # Revisión: rAñoMesDía.Gitcommit (8 caracteres de fecha y 7 primeros de commit).
[663363a]1293                if [ "$BRANCH" = "master" ]; then
1294                        REVISION=$(curl -s "$API_URL" | jq '"r" + (.commit.commit.committer.date | split("-") | join("")[:8]) + "." + (.commit.sha[:7])')
1295                else
1296                        REVISION=$(curl -s "$API_URL" | jq '"r" + (.commit.committer.date | split("-") | join("")[:8]) + "." + (.sha[:7])')
1297                fi
[5f0c2dd]1298        else
1299                # Parámetro "release" del fichero JSON.
1300                REVISION=$(jq -r '.release' $PROGRAMDIR/../doc/VERSION.json 2>/dev/null)
1301        fi
[3bbaf79]1302        [ -f $VERSIONFILE ] || echo '{ "project": "OpenGnsys" }' > $VERSIONFILE
1303        jq ".release=$REVISION" $VERSIONFILE | sponge $VERSIONFILE
1304        VERSION="$(jq -r '[.project, .version, .codename, .release] | join(" ")' $VERSIONFILE 2>/dev/null)"
1305        # Borrar antiguo fichero de versión.
1306        rm -f "${VERSIONFILE/json/txt}"
[eb9424f]1307
1308        echo
[5f21d34]1309        echoAndLog "OpenGnsys Update Summary"
[df3cd7f]1310        echo       "========================"
[3bbaf79]1311        echoAndLog "Project version:                  $VERSION"
[57f7e9c]1312        echoAndLog "Update log file:                  $LOG_FILE"
[c3e4ff1]1313        [ "$NEWFILES" ] && echoAndLog "Check new config files:           $(echo $NEWFILES)"
1314        [ "$NEWSERVICES" ] && echoAndLog "New compiled services:            $(echo $NEWSERVICES)"
[8b2da718]1315        echoAndLog "Warnings:"
[0304465]1316        echoAndLog " - You must to clear web browser cache before loading OpenGnsys page"
[dde2db1]1317        echoAndLog " - Run \"settoken\" script to update authentication tokens"
[c3e4ff1]1318        [ "$INSTALLEDOGLIVE" ] && echoAndLog " - Installed new ogLive Client: $INSTALLEDOGLIVE"
[d3c5538]1319        echoAndLog " - Review syslog configuration and logrotate by syslog,"
1320        echoAndLog "      in debug mode OpenGnsys log is very extensive."
[ce63f8d]1321
[eb9424f]1322        echo
1323}
1324
1325
[a0867b37]1326
1327#####################################################################
[5f21d34]1328####### Proceso de actualización de OpenGnsys
[a0867b37]1329#####################################################################
1330
1331
[27dc5ff]1332# Comprobar si hay conexión y detectar parámetros de red por defecto.
1333checkNetworkConnection
1334if [ $? -ne 0 ]; then
1335        errorAndLog "Error connecting to server. Causes:"
[0304465]1336        errorAndLog " - Network is unreachable, check device parameters"
1337        errorAndLog " - You are inside a private network, configure the proxy service"
1338        errorAndLog " - Server is temporally down, try again later"
[27dc5ff]1339        exit 1
1340fi
[739fb00]1341getNetworkSettings
[27dc5ff]1342
[fd45e9a]1343# Elegir versión y comprobar si se intanta actualizar a una versión anterior.
1344chooseVersion
[0304465]1345checkVersion
1346if [ $? -ne 0 ]; then
1347        errorAndLog "Cannot downgrade to an older version ($OLDVERSION to $NEWVERSION)"
1348        errorAndLog "You must to uninstall OpenGnsys and install desired release"
1349        exit 1
1350fi
1351
[663363a]1352echoAndLog "OpenGnsys update begins at $(date)"
1353pushd $WORKDIR
1354
[64dd765]1355# Comprobar auto-actualización del programa.
1356if [ "$PROGRAMDIR" != "$INSTALL_TARGET/bin" ]; then
1357        checkAutoUpdate
1358        if [ $? -ne 0 ]; then
[0304465]1359                echoAndLog "OpenGnsys updater has been overwritten"
[063caa5]1360                echoAndLog "Please, run this script again"
[64dd765]1361                exit
1362        fi
1363fi
1364
[db9e706]1365# Detectar datos de auto-configuración del instalador.
1366autoConfigure
1367
[bb30a50]1368# Instalar dependencias.
[d70a45f]1369installDependencies ${DEPENDENCIES[*]}
[a0867b37]1370if [ $? -ne 0 ]; then
[0304465]1371        errorAndLog "Error: you must to install all needed dependencies"
[a0867b37]1372        exit 1
1373fi
1374
[5f21d34]1375# Arbol de directorios de OpenGnsys.
[a0867b37]1376createDirs ${INSTALL_TARGET}
1377if [ $? -ne 0 ]; then
[0304465]1378        errorAndLog "Error while creating directory paths"
[a0867b37]1379        exit 1
1380fi
1381
1382# Si es necesario, descarga el repositorio de código en directorio temporal
[884b6ce]1383if [ $REMOTE -eq 1 ]; then
1384        downloadCode $CODE_URL
[a0867b37]1385        if [ $? -ne 0 ]; then
[884b6ce]1386                errorAndLog "Error while getting code from repository"
[a0867b37]1387                exit 1
1388        fi
1389else
1390        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
1391fi
1392
[21372e8]1393# Comprobar configuración de MySQL.
1394checkMysqlConfig $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD
1395
[566e84f]1396# Actualizar la BD.
1397updateDatabase
[295b4ab]1398
1399# Actualizar ficheros complementarios del servidor
[a0867b37]1400updateServerFiles
1401if [ $? -ne 0 ]; then
[5f21d34]1402        errorAndLog "Error updating OpenGnsys Server files"
[a0867b37]1403        exit 1
1404fi
1405
[be49575]1406# Configurar Rsync.
1407rsyncConfigure
1408
[5050850]1409# Actualizar ficheros del cliente.
[295b4ab]1410updateClientFiles
[5050850]1411createCerts
[295b4ab]1412updateInterfaceAdm
[45f1fe8]1413
[5050850]1414# Actualizar páqinas web.
[3ce53a7]1415apacheConfiguration
[a0867b37]1416updateWebFiles
1417if [ $? -ne 0 ]; then
[5f21d34]1418        errorAndLog "Error updating OpenGnsys Web Admin files"
[a0867b37]1419        exit 1
1420fi
[ec045b1]1421# Actaulizar ficheros descargables.
1422updateDownloadableFiles
[5d6bf97]1423# Generar páginas Doxygen para instalar en el web
1424makeDoxygenFiles
[a0867b37]1425
[bb30a50]1426# Recompilar y actualizar los servicios del sistema
[c070d3d]1427if ogServerCompilation; then
[c3e4ff1]1428        # Restart services, if necessary.
1429        if [ "$NEWSERVICES" ]; then
1430                echoAndLog "Restarting OpenGnsys services"
1431                service="opengnsys" $STARTSERVICE
[1718dc0]1432                service="ogserver" $STARTSERVICE
[c3e4ff1]1433        fi
1434else
1435        errorAndLog "Error compiling OpenGnsys services"
1436        exit 1
1437fi
[bb30a50]1438
1439# Actaulizar ficheros auxiliares del cliente
[a0867b37]1440updateClient
1441if [ $? -ne 0 ]; then
[0304465]1442        errorAndLog "Error updating client files"
[a0867b37]1443        exit 1
1444fi
1445
[affce16]1446# Update ogClient
1447if ! updateOgClient; then
1448        errorAndLog "Error updating ogClient files"
1449        exit 1
1450fi
1451
[5b95ab6]1452# Comprobar permisos y ficheros.
1453checkFiles
[3320409]1454
[eb9424f]1455# Mostrar resumen de actualización.
1456updateSummary
1457
[3b8ef0d]1458rm -rf $WORKDIR
[5f21d34]1459echoAndLog "OpenGnsys update finished at $(date)"
[a0867b37]1460
1461popd
1462
Note: See TracBrowser for help on using the repository browser.