source: installer/opengnsys_update.sh @ 527cd97

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacion
Last change on this file since 527cd97 was 4f64fa1, checked in by Ramón M. Gómez <ramongomez@…>, 6 years ago

#912: Fix bugs in update script: generating a new repository access token and uncompressing downloaded code; update closed tickets list.

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