source: installer/opengnsys_update.sh @ d1de0b2

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

#981 Add systemd unit file

The ogAdmServer needs to be started after MySQL, because it queries the
DB at the beginning to obtain the schedules.

This commit adds a systemd unit file that force OpenGnsys service to
start after MySQL service

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