source: installer/opengnsys_update.sh @ 5d05b06

Last change on this file since 5d05b06 was e7ffae8, checked in by OpenGnSys Support Team <soporte-og@…>, 4 years ago

#988 Add ogserver.json creation when running opengnsys_update.sh

This patch enables the creation of a default json config for the
ogserver when running opengnsys_update.sh, if no prior json config
is detected.

Eg. when updating from 1.1.1c to 1.2.0

Reviewed-by: Jose M. Guisado <jguisado@…>

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