source: installer/opengnsys_update.sh @ 576c9e6

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

#784: Using PHP-FPM instead of Mod-PHP to improve Apache performance.

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