source: installer/opengnsys_installer.sh @ 38feca6

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

#988 Add ogServer JSON config to installer

This commit changes legacy ogServer configuration file to new ogServer
JSON configuration file.

  • Property mode set to 100755
File size: 60.3 KB
RevLine 
[a01156a]1#!/bin/bash
2
3#####################################################################
[5f21d34]4####### Script instalador OpenGnsys
5####### Autor: Luis Guillén <lguillen@unizar.es>
[a01156a]6#####################################################################
7
8
[8ca0cc9]9#####################################################################
10####### Funciones de configuración
11#####################################################################
[9672640]12
[8ca0cc9]13# Devuelve en la variable PASSWORD la clave introducida por el usuario (o la indicada por defecto)
14function enterPassword ()
15{
16        local PASSWORD2
17        local DEFAULT_PASSWORD="$1"
18
19        while : ; do
20                stty -echo
21                read -r PASSWORD
22                stty echo
23                if [ -z "$PASSWORD" ]; then
24                        # Si esta vacio ponemos el valor por defecto
25                        PASSWORD="${PASSWORD:-$DEFAULT_PASSWORD}"
26                        break
27                else
28                        if [ -n "${PASSWORD//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico
29                                echo -e "\\aERROR: Password must be alphanumeric, try again..."
30                        else
31                                echo -n -e "\\nConfirm password: "
32                                stty -echo
33                                read -r PASSWORD2
34                                stty echo
35                                if [ "$PASSWORD" == "$PASSWORD2" ]; then
36                                        break
37                                else
38                                        echo -e "\\aERROR: Passwords don't match, try again."
39                                fi
40                        fi
41                fi
42                echo -n -e "Please, enter a new password (${DEFAULT_PASSWORD}): "
43        done
44}
[9672640]45
[8ca0cc9]46# Recoge los datos de configuración introducidos por el usuario.
47function userData ()
48{
49        ####  AVISO: Puede editar configuración de acceso por defecto.
50        ####  WARNING: Edit default access configuration if you wish.
51        DEFAULT_MYSQL_ROOT_PASSWORD="passwordroot"      # Clave por defecto root de MySQL
52        DEFAULT_OPENGNSYS_DB_USER="usuog"               # Usuario por defecto de acceso a la base de datos
53        DEFAULT_OPENGNSYS_DB_PASSWD="passusuog"         # Clave por defecto de acceso a la base de datos
54        DEFAULT_OPENGNSYS_CLIENT_PASSWD="og"            # Clave por defecto de acceso del cliente       
[2e1b900]55        DEFAULT_OGLIVE="ogLive-bionic-5.0.0-27-generic-amd64-r20190830.7208cc9.iso"     # Cliente ogLive
[8ca0cc9]56
57        echo -e "\\nOpenGnsys Installation"
58        echo "=============================="
59
[5c82233]60        if [[ $- =~ s ]]; then
61                echo -e "\\nNot interactive mode: setting default configuration values.\\n"
62                MYSQL_ROOT_PASSWORD="$DEFAULT_MYSQL_ROOT_PASSWORD"
63                OPENGNSYS_DB_USER="$DEFAULT_OPENGNSYS_DB_USER"
64                OPENGNSYS_DB_PASSWD="$DEFAULT_OPENGNSYS_DB_PASSWD"
65                OPENGNSYS_CLIENT_PASSWD="$DEFAULT_OPENGNSYS_CLIENT_PASSWD"
66                OGLIVE="$DEFAULT_OGLIVE"
67                return
68        fi
69
[8ca0cc9]70        # Clave root de MySQL
71        echo -n -e "\\nEnter root password for MySQL (${DEFAULT_MYSQL_ROOT_PASSWORD}): "
72        enterPassword "$DEFAULT_MYSQL_ROOT_PASSWORD"
73        MYSQL_ROOT_PASSWORD="$PASSWORD"
74
75        # Usuario de acceso a la base de datos
76        while : ; do
77                echo -n -e "\\n\\nEnter username for OpenGnsys console (${DEFAULT_OPENGNSYS_DB_USER}): "
78                read -r OPENGNSYS_DB_USER
79                if [ -n "${OPENGNSYS_DB_USER//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico
80                        echo -e "\\aERROR: Must be alphanumeric, try again..."
81                else
82                        # Si esta vacio ponemos el valor por defecto
83                        OPENGNSYS_DB_USER="${OPENGNSYS_DB_USER:-$DEFAULT_OPENGNSYS_DB_USER}"
84                        break
85                fi
86        done
[9672640]87
[8ca0cc9]88        # Clave de acceso a la base de datos
[5f21d34]89        echo -n -e "\\nEnter password for OpenGnsys console (${DEFAULT_OPENGNSYS_DB_PASSWD}): "
[8ca0cc9]90        enterPassword "$DEFAULT_OPENGNSYS_DB_PASSWD"
91        OPENGNSYS_DB_PASSWD="$PASSWORD"
92
93        # Clave de acceso del cliente
94        echo -n -e "\\n\\nEnter root password for OpenGnsys client (${DEFAULT_OPENGNSYS_CLIENT_PASSWD}): "
95        enterPassword "$DEFAULT_OPENGNSYS_CLIENT_PASSWD"
96        OPENGNSYS_CLIENT_PASSWD="$PASSWORD"
97        unset PASSWORD
98
99        # Selección de clientes ogLive para descargar.
100        while : ; do
101                echo -e "\\n\\nChoose ogLive client to install."
102                echo -e "1) Kernel 5.0, 64-bit, EFI-compatible"
103                echo -e "2) Kernel 3.2, 32-bit"
104                echo -e "3) Both"
105                echo -n -e "Please, type a valid number (1): "
106                read -r OPT
107                case "$OPT" in
[9345a1f]108                        1|"")   OGLIVE="$DEFAULT_OGLIVE"
[8ca0cc9]109                                break ;;
110                        2)      OGLIVE="ogLive-precise-3.2.0-23-generic-r5159.iso"
111                                break ;;
[9345a1f]112                        3)      OGLIVE=" $DEFAULT_OGLIVE ogLive-precise-3.2.0-23-generic-r5159.iso";
[8ca0cc9]113                                break ;;
114                        *)      echo -e "\\aERROR: unknown option, try again."
115                esac
116        done
[3aaf91d]117
[8ca0cc9]118        echo -e "\\n=============================="
119}
[a01156a]120
[8ca0cc9]121# Asigna valores globales de configuración para el script.
122function globalSetup ()
123{
124        PROGRAMDIR=$(readlink -e "$(dirname "$0")")
125        PROGRAMNAME=$(basename "$0")
126
127        # Comprobar si se ha descargado el paquete comprimido (REMOTE=0) o sólo el instalador (REMOTE=1).
128        OPENGNSYS_SERVER="opengnsys.es"
129        DOWNLOADURL="https://$OPENGNSYS_SERVER/trac/downloads"
130        if [ -d "$PROGRAMDIR/../installer" ]; then
131                REMOTE=0
132        else
133                REMOTE=1
134        fi
[994e413]135        BRANCH="master"
[8ca0cc9]136        CODE_URL="https://codeload.github.com/opengnsys/OpenGnsys/zip/$BRANCH"
[6ab13a3]137        API_URL="https://api.github.com/repos/opengnsys/OpenGnsys"
[8ca0cc9]138
139        # Directorios de instalación y destino de OpenGnsys.
140        WORKDIR=/tmp/opengnsys_installer
141        INSTALL_TARGET=/opt/opengnsys
142        PATH=$PATH:$INSTALL_TARGET/bin
143
144        # Registro de incidencias.
145        OGLOGFILE=$INSTALL_TARGET/log/${PROGRAMNAME%.sh}.log
146        LOG_FILE=/tmp/$(basename $OGLOGFILE)
147
148        # Usuario del cliente para acceso remoto.
149        OPENGNSYS_CLIENT_USER="opengnsys"
150        # Nombre de la base datos y fichero SQL para su creación.
151        OPENGNSYS_DATABASE="ogAdmBD"
152        OPENGNSYS_DB_CREATION_FILE=opengnsys/admin/Database/${OPENGNSYS_DATABASE}.sql
153}
[d168a46]154
155# Generar variables de configuración del instalador
156# Variables globales:
[5cc52295]157# - OSDISTRIB, OSVERSION - tipo y versión de la distribución GNU/Linux
[d168a46]158# - DEPENDENCIES - array de dependencias que deben estar instaladas
159# - UPDATEPKGLIST, INSTALLPKGS, CHECKPKGS - comandos para gestión de paquetes
[109e8b2]160# - INSTALLEXTRADEPS - instalar dependencias no incluidas en la distribución
[53fba30]161# - STARTSERVICE, ENABLESERVICE - iniciar y habilitar un servicio
[109e8b2]162# - STOPSERVICE, DISABLESERVICE - parar y deshabilitar un servicio
[53fba30]163# - APACHESERV, APACHECFGDIR, APACHESITESDIR, APACHEUSER, APACHEGROUP - servicio y configuración de Apache
[9215580]164# - APACHEENABLEMODS, APACHEENABLESSL, APACHEMAKECERT - habilitar módulos y certificado SSL
[5f21d34]165# - APACHEENABLEOG, APACHEOGSITE, - habilitar sitio web de OpenGnsys
[9215580]166# - PHPFPMSERV - servicio PHP FastCGI Process Manager para Apache
[53fba30]167# - INETDSERV - servicio Inetd
168# - DHCPSERV, DHCPCFGDIR - servicio y configuración de DHCP
[0f8100d]169# - MYSQLSERV, TMPMYCNF - servicio MySQL y fichero temporal con credenciales de acceso
170# - MARIADBSERV - servicio MariaDB (sustituto de MySQL en algunas distribuciones)
[e70925a]171# - RSYNCSERV, RSYNCCFGDIR - servicio y configuración de Rsync
[53fba30]172# - SAMBASERV, SAMBACFGDIR - servicio y configuración de Samba
[a16ce1b]173# - TFTPSERV, TFTPCFGDIR - servicio y configuración de TFTP/PXE
[d168a46]174function autoConfigure()
175{
[44f6582]176# Detectar sistema operativo del servidor (compatible con fichero os-release y con LSB).
177if [ -f /etc/os-release ]; then
178        source /etc/os-release
[eb7b39d]179        OSDISTRIB="$ID"
[5cc52295]180        OSVERSION="$VERSION_ID"
[44f6582]181else
182        OSDISTRIB=$(lsb_release -is 2>/dev/null)
[5cc52295]183        OSVERSION=$(lsb_release -rs 2>/dev/null)
[44f6582]184fi
[5cc52295]185# Convertir distribución a minúsculas y obtener solo el 1er número de versión.
[eb7b39d]186OSDISTRIB="${OSDISTRIB,,}"
[5cc52295]187OSVERSION="${OSVERSION%%.*}"
[d168a46]188
[eb7b39d]189# Configuración según la distribución GNU/Linux (usar minúsculas).
[d168a46]190case "$OSDISTRIB" in
[eb7b39d]191        ubuntu|debian|linuxmint)
[0e3e167]192                DEPENDENCIES=( subversion apache2 php php-ldap php-fpm mysql-server php-mysql isc-dhcp-server bittorrent tftp-hpa tftpd-hpa xinetd build-essential g++-multilib libmysqlclient-dev wget curl doxygen graphviz bittornado ctorrent samba rsync unzip netpipes debootstrap schroot squashfs-tools 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 gawk libdbi-dev libdbi1 libdbd-mysql automake liblz4-tool )
[d168a46]193                UPDATEPKGLIST="apt-get update"
194                INSTALLPKG="apt-get -y install --force-yes"
195                CHECKPKG="dpkg -s \$package 2>/dev/null | grep Status | grep -qw install"
[53fba30]196                if which service &>/dev/null; then
[7ba85a4]197                        STARTSERVICE="eval service \$service restart"
[109e8b2]198                        STOPSERVICE="eval service \$service stop"
[53fba30]199                else
[7ba85a4]200                        STARTSERVICE="eval /etc/init.d/\$service restart"
[109e8b2]201                        STOPSERVICE="eval /etc/init.d/\$service stop"
[53fba30]202                fi
[2c69d57]203                ENABLESERVICE="eval systemctl enable \$service.service"
204                DISABLESERVICE="eval systemctl disable \$service.service"
[53fba30]205                APACHESERV=apache2
[d168a46]206                APACHECFGDIR=/etc/apache2
[643ca8c]207                APACHESITESDIR=sites-available
[53fba30]208                APACHEOGSITE=opengnsys
[d168a46]209                APACHEUSER="www-data"
210                APACHEGROUP="www-data"
[9215580]211                APACHEENABLEMODS="a2enmod ssl rewrite proxy_fcgi fastcgi actions alias"
[7ba85a4]212                APACHEENABLESSL="a2ensite default-ssl"
[53fba30]213                APACHEENABLEOG="a2ensite $APACHEOGSITE"
[643ca8c]214                APACHEMAKECERT="make-ssl-cert generate-default-snakeoil --force-overwrite"
[53fba30]215                DHCPSERV=isc-dhcp-server
[83518d5]216                DHCPCFGDIR=/etc/dhcp
[f243a47]217                INETDSERV=xinetd
218                INETDCFGDIR=/etc/xinetd.d
[53fba30]219                MYSQLSERV=mysql
[08815ac]220                MYSQLCFGDIR=/etc/mysql/mysql.conf.d
[0f8100d]221                MARIADBSERV=mariadb
[9215580]222                PHPFPMSERV=php-fpm
[e70925a]223                RSYNCSERV=rsync
224                RSYNCCFGDIR=/etc
[53fba30]225                SAMBASERV=smbd
[d168a46]226                SAMBACFGDIR=/etc/samba
227                TFTPCFGDIR=/var/lib/tftpboot
228                ;;
[eb7b39d]229        fedora|centos)
[5ee13ae]230                DEPENDENCIES=( subversion httpd mod_ssl php-ldap php-fpm mysql-server mysql-devel mysql-devel.i686 php-mysql dhcp tftp-server tftp xinetd binutils gcc gcc-c++ glibc-devel glibc-devel.i686 glibc-static glibc-static.i686 libstdc++-devel.i686 make wget curl doxygen graphviz ctorrent samba samba-client rsync unzip debootstrap schroot squashfs-tools python-crypto arp-scan procps-ng gettext moreutils jq net-tools udpcast libev-devel jansson-devel openssl-devel shim-x64 grub2-efi-x64 grub2-efi-x64-modules gawk libdbi-devel libdbi libdbi-dbd-mysql automake http://ftp.altlinux.org/pub/distributions/ALTLinux/5.1/branch/$(arch)/RPMS.classic/netpipes-4.2-alt1.$(arch).rpm )
[97b6579]231                [ "$OSDISTRIB" == "centos" ] && UPDATEPKGLIST="yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-$OSVERSION.noarch.rpm http://rpms.remirepo.net/enterprise/remi-release-$OSVERSION.rpm"
232                INSTALLEXTRADEPS=( 'pushd /tmp; wget -t3 http://ftp.acc.umu.se/mirror/bittornado/BitTornado-0.3.18.tar.gz && tar xvzf BitTornado-0.3.18.tar.gz && cd BitTornado-CVS && python setup.py install && ln -fs btlaunchmany.py /usr/bin/btlaunchmany && ln -fs bttrack.py /usr/bin/bttrack; popd' )
233                INSTALLPKG="yum install -y libstdc++ libstdc++.i686"
[c79a2b3]234                CHECKPKG="rpm -q --quiet \$package"
[03cfd6e]235                SYSTEMD=$(which systemctl 2>/dev/null)
236                if [ -n "$SYSTEMD" ]; then
237                        STARTSERVICE="eval systemctl start \$service.service"
238                        STOPSERVICE="eval systemctl stop \$service.service"
239                        ENABLESERVICE="eval systemctl enable \$service.service"
240                        DISABLESERVICE="eval systemctl disable \$service.service"
241                else
242                        STARTSERVICE="eval service \$service start"
243                        STOPSERVICE="eval service \$service stop"
244                        ENABLESERVICE="eval chkconfig \$service on"
245                        DISABLESERVICE="eval chkconfig \$service off"
246                fi
[53fba30]247                APACHESERV=httpd
[d168a46]248                APACHECFGDIR=/etc/httpd/conf.d
[53fba30]249                APACHEOGSITE=opengnsys.conf
[d168a46]250                APACHEUSER="apache"
251                APACHEGROUP="apache"
[5f21d34]252                APACHEREWRITEMOD="sed -i '/rewrite/s/^#//' $APACHECFGDIR/../*.conf"
[53fba30]253                DHCPSERV=dhcpd
[d168a46]254                DHCPCFGDIR=/etc/dhcp
[53fba30]255                INETDSERV=xinetd
[f243a47]256                INETDCFGDIR=/etc/xinetd.d
[53fba30]257                MYSQLSERV=mysqld
[7d8d8af]258                MYSQLCFGDIR=/etc/my.cnf.d
[0f8100d]259                MARIADBSERV=mariadb
[ec536c6]260                PHPFPMSERV=php-fpm
[e70925a]261                RSYNCSERV=rsync
262                RSYNCCFGDIR=/etc
[53fba30]263                SAMBASERV=smb
[d168a46]264                SAMBACFGDIR=/etc/samba
[53fba30]265                TFTPSERV=tftp
[d168a46]266                TFTPCFGDIR=/var/lib/tftpboot
267                ;;
268        "")     echo "ERROR: Unknown Linux distribution, please install \"lsb_release\" command."
269                exit 1 ;;
[5f21d34]270        *)      echo "ERROR: Distribution not supported by OpenGnsys."
[d168a46]271                exit 1 ;;
272esac
[09bf701]273
274# Fichero de credenciales de acceso a MySQL.
275TMPMYCNF=/tmp/.my.cnf.$$
[d168a46]276}
277
[09ac3b8]278
[ff6c349]279# Modificar variables de configuración tras instalar paquetes del sistema.
280function autoConfigurePost()
281{
[e432478]282local f MKNETDIR
[09ac3b8]283
[44f6582]284# Configuraciones específicas para Samba y TFTP en Debian 6.
285[ -z "$SYSTEMD" -a ! -e /etc/init.d/$SAMBASERV ] && SAMBASERV=samba
286[ ! -e $TFTPCFGDIR ] && TFTPCFGDIR=/srv/tftp
287
[e432478]288# Preparar arranque en red con Grub.
289for f in grub-mknetdir grub2-mknetdir; do
290        if which $f &>/dev/null; then MKNETDIR=$f; fi
[09ac3b8]291done
[e432478]292$MKNETDIR --net-directory=$TFTPCFGDIR --subdir=grub
[ff6c349]293}
294
295
[83518d5]296# Cargar lista de paquetes del sistema y actualizar algunas variables de configuración
297# dependiendo de la versión instalada.
298function updatePackageList()
299{
[a37e5fc4]300local DHCPVERSION PHP7VERSION
[83518d5]301
302# Si es necesario, actualizar la lista de paquetes disponibles.
303[ -n "$UPDATEPKGLIST" ] && eval $UPDATEPKGLIST
304
305# Configuración personallizada de algunos paquetes.
306case "$OSDISTRIB" in
[eb7b39d]307        ubuntu|linuxmint)       # Postconfiguación personalizada para Ubuntu.
[83518d5]308                # Configuración para DHCP v3.
[e4b1572]309                DHCPVERSION=$(apt-cache show $(apt-cache pkgnames|egrep "dhcp.?-server$") | \
[83518d5]310                              awk '/Version/ {print substr($2,1,1);}' | \
311                              sort -n | tail -1)
312                if [ $DHCPVERSION = 3 ]; then
[e4b1572]313                        DEPENDENCIES=( ${DEPENDENCIES[@]/isc-dhcp-server/dhcp3-server} )
[53fba30]314                        DHCPSERV=dhcp3-server
[83518d5]315                        DHCPCFGDIR=/etc/dhcp3
316                fi
[a37e5fc4]317                # Configuración para PHP 7 en Ubuntu.
318                if [ -z "$(apt-cache pkgnames php7)" ]; then
[668f7dc]319                        eval $INSTALLPKG software-properties-common
[21f78d1]320                        add-apt-repository -y ppa:ondrej/php
[668f7dc]321                        eval $UPDATEPKGLIST
[5e4fb7e]322                        PHP7VERSION=$(apt-cache pkgnames php7 | sort | head -1)
[ec536c6]323                        PHPFPMSERV="${PHP7VERSION}-fpm"
[5e4fb7e]324                        DEPENDENCIES=( ${DEPENDENCIES[@]//php/$PHP7VERSION} )
[ad69c61]325                fi
[5e4fb7e]326                # Adaptar dependencias para libmysqlclient.
327                [ -z "$(apt-cache pkgnames libmysqlclient-dev)" ] && [ -n "$(apt-cache pkgnames libmysqlclient15)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//libmysqlclient-dev/libmysqlclient15} )
[9e64d82]328                # Paquete correcto para realpath.
329                [ -z "$(apt-cache pkgnames realpath)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//realpath/coreutils} )
[83518d5]330                ;;
[eb7b39d]331        centos) # Postconfiguación personalizada para CentOS.
[a37e5fc4]332                # Configuración para PHP 7.
[ec536c6]333                PHP7VERSION=$(yum list -q php7\* 2>/dev/null | awk -F. '/^php/ {print $1; exit;}')
[97b6579]334                PHPFPMSERV="${PHP7VERSION}-${PHPFPMSERV}"
335                DEPENDENCIES=( ${PHP7VERSION} ${DEPENDENCIES[@]//php/$PHP7VERSION-php} )
[2c8b9ed]336                # Cambios a aplicar a partir de CentOS 7.
337                if [ $OSVERSION -ge 7 ]; then
338                        # Sustituir MySQL por MariaDB.
339                        DEPENDENCIES=( ${DEPENDENCIES[*]/mysql-/mariadb-} )
[325aac9]340                        # Instalar ctorrent de EPEL para CentOS 6 (no disponible en CentOS 7).
341                        DEPENDENCIES=( ${DEPENDENCIES[*]/ctorrent/http://dl.fedoraproject.org/pub/epel/6/$(arch)/Packages/c/ctorrent-1.3.4-14.dnh3.3.2.el6.$(arch).rpm} )
[2c8b9ed]342                fi
[c525453]343                ;;
[eb7b39d]344        fedora) # Postconfiguación personalizada para Fedora.
[c525453]345                # Incluir paquetes específicos.
[325aac9]346                DEPENDENCIES=( ${DEPENDENCIES[@]} btrfs-progs )
[5cc52295]347                # Sustituir MySQL por MariaDB a partir de Fedora 20.
348                [ $OSVERSION -ge 20 ] && DEPENDENCIES=( ${DEPENDENCIES[*]/mysql-/mariadb-} )
[c79a2b3]349                ;;
[83518d5]350esac
351}
352
[d168a46]353
354#####################################################################
[a01156a]355####### Algunas funciones útiles de propósito general:
356#####################################################################
[d168a46]357
[13a01a7]358function getDateTime()
[a01156a]359{
[d168a46]360        date "+%Y%m%d-%H%M%S"
[a01156a]361}
362
363# Escribe a fichero y muestra por pantalla
[13a01a7]364function echoAndLog()
[a01156a]365{
[d168a46]366        local DATETIME=`getDateTime`
[87c7b02]367        echo "$1"
[d168a46]368        echo "$DATETIME;$SSH_CLIENT;$1" >> $LOG_FILE
[a01156a]369}
370
[87c7b02]371# Escribe a fichero y muestra mensaje de error
[13a01a7]372function errorAndLog()
[a01156a]373{
[d168a46]374        local DATETIME=`getDateTime`
[87c7b02]375        echo "ERROR: $1"
[d168a46]376        echo "$DATETIME;$SSH_CLIENT;ERROR: $1" >> $LOG_FILE
[a01156a]377}
378
[346eaee]379# Escribe a fichero y muestra mensaje de aviso
380function warningAndLog()
381{
382        local DATETIME=`getDateTime`
[cd86637]383        echo "Warning: $1"
[346eaee]384        echo "$DATETIME;$SSH_CLIENT;Warning: $1" >> $LOG_FILE
385}
386
[87c7b02]387# Comprueba si el elemento pasado en $2 está en el array $1
[13a01a7]388function isInArray()
[a01156a]389{
390        if [ $# -ne 2 ]; then
[13a01a7]391                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]392                exit 1
393        fi
394
395        local deps
[87c7b02]396        local is_in_array=1
397        local element="$2"
398
399        echoAndLog "${FUNCNAME}(): checking if $2 is in $1"
[5c33840]400        eval "deps=( \"\${$1[@]}\" )"
[a01156a]401
[87c7b02]402        # Copia local del array del parámetro 1.
403        for (( i = 0 ; i < ${#deps[@]} ; i++ )); do
404                if [ "${deps[$i]}" = "${element}" ]; then
405                        echoAndLog "isInArray(): $element found in array"
[a01156a]406                        is_in_array=0
407                fi
408        done
409
410        if [ $is_in_array -ne 0 ]; then
[87c7b02]411                echoAndLog "${FUNCNAME}(): $element NOT found in array"
[a01156a]412        fi
413
414        return $is_in_array
415}
416
[87c7b02]417
[a01156a]418#####################################################################
419####### Funciones de manejo de paquetes Debian
420#####################################################################
421
[13a01a7]422function checkPackage()
[a01156a]423{
424        package=$1
425        if [ -z $package ]; then
[73cfa0a]426                errorAndLog "${FUNCNAME}(): parameter required"
[a01156a]427                exit 1
428        fi
[73cfa0a]429        echoAndLog "${FUNCNAME}(): checking if package $package exists"
[d168a46]430        eval $CHECKPKG
[a01156a]431        if [ $? -eq 0 ]; then
[73cfa0a]432                echoAndLog "${FUNCNAME}(): package $package exists"
[a01156a]433                return 0
434        else
[73cfa0a]435                echoAndLog "${FUNCNAME}(): package $package doesn't exists"
[a01156a]436                return 1
437        fi
438}
439
[87c7b02]440# Recibe array con dependencias
[a01156a]441# por referencia deja un array con las dependencias no resueltas
442# devuelve 1 si hay alguna dependencia no resuelta
[13a01a7]443function checkDependencies()
[a01156a]444{
445        if [ $# -ne 2 ]; then
[73cfa0a]446                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]447                exit 1
448        fi
449
[73cfa0a]450        echoAndLog "${FUNCNAME}(): checking dependences"
[a01156a]451        uncompletedeps=0
452
453        # copia local del array del parametro 1
454        local deps
[5c33840]455        eval "deps=( \"\${$1[@]}\" )"
[a01156a]456
457        declare -a local_notinstalled
[5c33840]458
[a01156a]459        for (( i = 0 ; i < ${#deps[@]} ; i++ ))
460        do
461                checkPackage ${deps[$i]}
462                if [ $? -ne 0 ]; then
463                        local_notinstalled[$uncompletedeps]=$package
464                        let uncompletedeps=uncompletedeps+1
465                fi
466        done
467
468        # relleno el array especificado en $2 por referencia
469        for (( i = 0 ; i < ${#local_notinstalled[@]} ; i++ ))
470        do
471                eval "${2}[$i]=${local_notinstalled[$i]}"
472        done
473
474        # retorna el numero de paquetes no resueltos
[73cfa0a]475        echoAndLog "${FUNCNAME}(): dependencies uncompleted: $uncompletedeps"
[a01156a]476        return $uncompletedeps
477}
478
479# Recibe un array con las dependencias y lo instala
[13a01a7]480function installDependencies()
[a01156a]481{
482        if [ $# -ne 1 ]; then
[813f617]483                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]484                exit 1
485        fi
[813f617]486        echoAndLog "${FUNCNAME}(): installing uncompleted dependencies"
[a01156a]487
488        # copia local del array del parametro 1
489        local deps
[5c33840]490        eval "deps=( \"\${$1[@]}\" )"
[a01156a]491
492        local string_deps=""
493        for (( i = 0 ; i < ${#deps[@]} ; i++ ))
494        do
495                string_deps="$string_deps ${deps[$i]}"
496        done
497
498        if [ -z "${string_deps}" ]; then
[813f617]499                errorAndLog "${FUNCNAME}(): array of dependeces is empty"
[a01156a]500                exit 1
501        fi
502
[c79a2b3]503        OLD_DEBIAN_FRONTEND=$DEBIAN_FRONTEND            # Debian/Ubuntu
[a01156a]504        export DEBIAN_FRONTEND=noninteractive
505
[d168a46]506        echoAndLog "${FUNCNAME}(): now $string_deps will be installed"
507        eval $INSTALLPKG $string_deps
[a01156a]508        if [ $? -ne 0 ]; then
[813f617]509                errorAndLog "${FUNCNAME}(): error installing dependencies"
[a01156a]510                return 1
511        fi
512
[c79a2b3]513        DEBIAN_FRONTEND=$OLD_DEBIAN_FRONTEND            # Debian/Ubuntu
[6019b12]514        test grep -q "EPEL temporal" /etc/yum.repos.d/epel.repo 2>/dev/null || mv -f /etc/yum.repos.d/epel.repo.rpmnew /etc/yum.repos.d/epel.repo 2>/dev/null   # CentOS/RedHat EPEL
[c79a2b3]515
[813f617]516        echoAndLog "${FUNCNAME}(): dependencies installed"
[a01156a]517}
518
[13a01a7]519# Hace un backup del fichero pasado por parámetro
520# deja un -last y uno para el día
521function backupFile()
522{
523        if [ $# -ne 1 ]; then
524                errorAndLog "${FUNCNAME}(): invalid number of parameters"
525                exit 1
526        fi
527
[d168a46]528        local file="$1"
529        local dateymd=`date +%Y%m%d`
[13a01a7]530
[d168a46]531        if [ ! -f "$file" ]; then
[346eaee]532                warningAndLog "${FUNCNAME}(): file $file doesn't exists"
[13a01a7]533                return 1
534        fi
535
[d168a46]536        echoAndLog "${FUNCNAME}(): making $file backup"
[13a01a7]537
538        # realiza una copia de la última configuración como last
[d168a46]539        cp -a "$file" "${file}-LAST"
[13a01a7]540
541        # si para el día no hay backup lo hace, sino no
[d168a46]542        if [ ! -f "${file}-${dateymd}" ]; then
543                cp -a "$file" "${file}-${dateymd}"
[13a01a7]544        fi
545
[d168a46]546        echoAndLog "${FUNCNAME}(): $file backup success"
[13a01a7]547}
548
[a01156a]549#####################################################################
550####### Funciones para el manejo de bases de datos
551#####################################################################
552
553# This function set password to root
[13a01a7]554function mysqlSetRootPassword()
[a01156a]555{
556        if [ $# -ne 1 ]; then
[813f617]557                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]558                exit 1
559        fi
560
[e0edc14]561        local root_mysql="$1"
[813f617]562        echoAndLog "${FUNCNAME}(): setting root password in MySQL server"
[e0edc14]563        mysqladmin -u root password "$root_mysql"
[a01156a]564        if [ $? -ne 0 ]; then
[813f617]565                errorAndLog "${FUNCNAME}(): error while setting root password in MySQL server"
[a01156a]566                return 1
567        fi
[813f617]568        echoAndLog "${FUNCNAME}(): root password saved!"
[a01156a]569        return 0
570}
571
[892606b9]572# Si el servicio mysql esta ya instalado cambia la variable de la clave del root por la ya existente
[e0edc14]573function mysqlGetRootPassword()
574{
[892606b9]575        local pass_mysql
576        local pass_mysql2
[7c54b49]577        # Comprobar si MySQL está instalado con la clave de root por defecto.
578        if mysql -u root -p"$MYSQL_ROOT_PASSWORD" <<<"quit" 2>/dev/null; then
579                echoAndLog "${FUNCNAME}(): Using default mysql root password."
580        else
581                stty -echo
[e0edc14]582                echo "There is a MySQL service already installed."
583                read -p "Enter MySQL root password: " pass_mysql
[7c54b49]584                echo ""
[e0edc14]585                read -p "Confrim password:" pass_mysql2
[7c54b49]586                echo ""
587                stty echo
588                if [ "$pass_mysql" == "$pass_mysql2" ] ;then
[e0edc14]589                        MYSQL_ROOT_PASSWORD="$pass_mysql"
[7c54b49]590                        return 0
591                else
[e0edc14]592                        echo "The keys don't match. Do not configure the server's key,"
593                        echo "transactions in the database will give error."
[7c54b49]594                        return 1
595                fi
[892606b9]596        fi
597}
598
[a01156a]599# comprueba si puede conectar con mysql con el usuario root
600function mysqlTestConnection()
601{
602        if [ $# -ne 1 ]; then
[e0edc14]603                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]604                exit 1
605        fi
606
[09bf701]607        local root_password="$1"
[e0edc14]608        echoAndLog "${FUNCNAME}(): checking connection to mysql..."
[09bf701]609        # Componer fichero con credenciales de conexión a MySQL.
610        touch $TMPMYCNF
611        chmod 600 $TMPMYCNF
612        cat << EOT > $TMPMYCNF
[c073224]613[client]
[09bf701]614user=root
615password=$root_password
616EOT
617        # Borrar el fichero temporal si termina el proceso de instalación.
618        trap "rm -f $TMPMYCNF" 0 1 2 3 6 9 15
619        # Comprobar conexión a MySQL.
620        echo "" | mysql --defaults-extra-file=$TMPMYCNF
[a01156a]621        if [ $? -ne 0 ]; then
[e0edc14]622                errorAndLog "${FUNCNAME}(): connection to mysql failed, check root password and if daemon is running!"
[a01156a]623                return 1
624        else
[e0edc14]625                echoAndLog "${FUNCNAME}(): connection success"
[a01156a]626                return 0
627        fi
628}
629
630# comprueba si la base de datos existe
631function mysqlDbExists()
632{
[09bf701]633        if [ $# -ne 1 ]; then
[e0edc14]634                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]635                exit 1
636        fi
637
[09bf701]638        local database="$1"
[e0edc14]639        echoAndLog "${FUNCNAME}(): checking if $database exists..."
[09bf701]640        echo "show databases" | mysql --defaults-extra-file=$TMPMYCNF | grep "^${database}$"
[a01156a]641        if [ $? -ne 0 ]; then
[e0edc14]642                echoAndLog "${FUNCNAME}():database $database doesn't exists"
[a01156a]643                return 1
644        else
[e0edc14]645                echoAndLog "${FUNCNAME}():database $database exists"
[a01156a]646                return 0
647        fi
648}
649
[0a735488]650# Comprueba si la base de datos está vacía.
[a01156a]651function mysqlCheckDbIsEmpty()
652{
[09bf701]653        if [ $# -ne 1 ]; then
[e0edc14]654                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]655                exit 1
656        fi
657
[09bf701]658        local database="$1"
[e0edc14]659        echoAndLog "${FUNCNAME}(): checking if $database is empty..."
[09bf701]660        num_tablas=`echo "show tables" | mysql --defaults-extra-file=$TMPMYCNF "${database}" | wc -l`
[a01156a]661        if [ $? -ne 0 ]; then
[e0edc14]662                errorAndLog "${FUNCNAME}(): error executing query, check database and root password"
[a01156a]663                exit 1
664        fi
665
666        if [ $num_tablas -eq 0 ]; then
[e0edc14]667                echoAndLog "${FUNCNAME}():database $database is empty"
[a01156a]668                return 0
669        else
[e0edc14]670                echoAndLog "${FUNCNAME}():database $database has tables"
[a01156a]671                return 1
672        fi
673
674}
675
[0a735488]676# Importa un fichero SQL en la base de datos.
677# Parámetros:
678# - 1: nombre de la BD.
679# - 2: fichero a importar.
680# Nota: el fichero SQL puede contener las siguientes palabras reservadas:
681# - SERVERIP: se sustituye por la dirección IP del servidor.
682# - DBUSER: se sustituye por usuario de conexión a la BD definido en este script.
683# - DBPASSWD: se sustituye por la clave de conexión a la BD definida en este script.
[a01156a]684function mysqlImportSqlFileToDb()
685{
[09bf701]686        if [ $# -ne 2 ]; then
[c5ce04c]687                errorAndLog "${FNCNAME}(): invalid number of parameters"
[a01156a]688                exit 1
689        fi
690
[09bf701]691        local database="$1"
692        local sqlfile="$2"
[c4321ae]693        local tmpfile=$(mktemp)
[d168a46]694        local i=0
695        local dev=""
[c4321ae]696        local status
[a01156a]697
698        if [ ! -f $sqlfile ]; then
[c5ce04c]699                errorAndLog "${FUNCNAME}(): Unable to locate $sqlfile!!"
[a01156a]700                return 1
701        fi
702
[d168a46]703        echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..."
[c4321ae]704        chmod 600 $tmpfile
[d168a46]705        for dev in ${DEVICE[*]}; do
[73a1bd6]706                if [ "${DEVICE[i]}" == "$DEFAULTDEV" ]; then
[d168a46]707                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
708                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
709                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
710                                $sqlfile > $tmpfile
711                fi
712                let i++
713        done
[09bf701]714        mysql --defaults-extra-file=$TMPMYCNF --default-character-set=utf8 "${database}" < $tmpfile
[c4321ae]715        status=$?
716        rm -f $tmpfile
717        if [ $status -ne 0 ]; then
[c5ce04c]718                errorAndLog "${FUNCNAME}(): error while importing $sqlfile in database $database"
[a01156a]719                return 1
720        fi
[c5ce04c]721        echoAndLog "${FUNCNAME}(): file imported to database $database"
[a01156a]722        return 0
723}
724
725# Crea la base de datos
726function mysqlCreateDb()
727{
[09bf701]728        if [ $# -ne 1 ]; then
[a555f49]729                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]730                exit 1
731        fi
732
[09bf701]733        local database="$1"
[a01156a]734
[a555f49]735        echoAndLog "${FUNCNAME}(): creating database..."
[09bf701]736        mysqladmin --defaults-extra-file=$TMPMYCNF create $database
[a01156a]737        if [ $? -ne 0 ]; then
[a555f49]738                errorAndLog "${FUNCNAME}(): error while creating database $database"
[a01156a]739                return 1
740        fi
[e47e131]741        # Quitar modo ONLY_FULL_GROUP_BY de MySQL (ticket #730).
742        mysql --defaults-extra-file=$TMPMYCNF -e "SET GLOBAL sql_mode=(SELECT TRIM(BOTH ',' FROM REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')));"
743
[a555f49]744        echoAndLog "${FUNCNAME}(): database $database created"
[a01156a]745        return 0
746}
747
[0a735488]748# Comprueba si ya está definido el usuario de acceso a la BD.
[a01156a]749function mysqlCheckUserExists()
750{
[09bf701]751        if [ $# -ne 1 ]; then
[e0edc14]752                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]753                exit 1
754        fi
755
[09bf701]756        local userdb="$1"
[a01156a]757
[e0edc14]758        echoAndLog "${FUNCNAME}(): checking if $userdb exists..."
[09bf701]759        echo "select user from user where user='${userdb}'\\G" |mysql --defaults-extra-file=$TMPMYCNF mysql | grep user
[a01156a]760        if [ $? -ne 0 ]; then
[e0edc14]761                echoAndLog "${FUNCNAME}(): user doesn't exists"
[a01156a]762                return 1
763        else
[e0edc14]764                echoAndLog "${FUNCNAME}(): user already exists"
[a01156a]765                return 0
766        fi
767
768}
769
770# Crea un usuario administrativo para la base de datos
771function mysqlCreateAdminUserToDb()
772{
[09bf701]773        if [ $# -ne 3 ]; then
[e0edc14]774                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]775                exit 1
776        fi
777
[09bf701]778        local database="$1"
779        local userdb="$2"
780        local passdb="$3"
[a01156a]781
[e0edc14]782        echoAndLog "${FUNCNAME}(): creating admin user ${userdb} to database ${database}"
[a01156a]783
784        cat > $WORKDIR/create_${database}.sql <<EOF
785GRANT USAGE ON *.* TO '${userdb}'@'localhost' IDENTIFIED BY '${passdb}' ;
786GRANT ALL PRIVILEGES ON ${database}.* TO '${userdb}'@'localhost' WITH GRANT OPTION ;
787FLUSH PRIVILEGES ;
788EOF
[09bf701]789        mysql --defaults-extra-file=$TMPMYCNF < $WORKDIR/create_${database}.sql
[a01156a]790        if [ $? -ne 0 ]; then
[e0edc14]791                errorAndLog "${FUNCNAME}(): error while creating user in mysql"
[a01156a]792                rm -f $WORKDIR/create_${database}.sql
793                return 1
794        else
[e0edc14]795                echoAndLog "${FUNCNAME}(): user created ok"
[a01156a]796                rm -f $WORKDIR/create_${database}.sql
797                return 0
798        fi
799}
800
801
802#####################################################################
[884b6ce]803####### Funciones para la descarga de código
[a01156a]804#####################################################################
805
[884b6ce]806# Obtiene el código fuente del proyecto desde el repositorio de GitHub.
807function downloadCode()
[13a01a7]808{
809        if [ $# -ne 1 ]; then
810                errorAndLog "${FUNCNAME}(): invalid number of parameters"
811                exit 1
812        fi
813
[6090a2d]814        local url="$1"
[13a01a7]815
[884b6ce]816        echoAndLog "${FUNCNAME}(): downloading code..."
[13a01a7]817
[884b6ce]818        curl "${url}" -o opengnsys.zip && unzip opengnsys.zip && mv "OpenGnsys-$BRANCH" opengnsys
[13a01a7]819        if [ $? -ne 0 ]; then
[5f21d34]820                errorAndLog "${FUNCNAME}(): error getting OpenGnsys code from $url"
[13a01a7]821                return 1
822        fi
[884b6ce]823        rm -f opengnsys.zip
824        echoAndLog "${FUNCNAME}(): code was downloaded"
[13a01a7]825        return 0
826}
827
828
[892606b9]829############################################################
[7586ca3]830###  Detectar red
831############################################################
832
[07c3a59]833# Comprobar si existe conexión.
834function checkNetworkConnection()
835{
[6bd2e1e]836        echoAndLog "${FUNCNAME}(): Checking OpenGnsys server connectivity."
[a0081b7]837        OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"opengnsys.es"}
[506c670]838        if which curl &>/dev/null; then
839                curl --connect-timeout 10 -s "https://$OPENGNSYS_SERVER/" -o /dev/null && \
840                        curl --connect-timeout 10 -s "http://$OPENGNSYS_SERVER/" -o /dev/null
841        elif which wget &>/dev/null; then
842                wget --spider -q "https://$OPENGNSYS_SERVER/" && \
843                        wget --spider -q "http://$OPENGNSYS_SERVER/"
[225e859]844        else
845                echoAndLog "${FUNCNAME}(): Cannot execute \"wget\" nor \"curl\"."
846                return 1
847        fi
[07c3a59]848}
849
[140fbd5]850# Convierte nº de bits (notación CIDR) en máscara de red (gracias a FriedZombie en openwrt.org).
851cidr2mask ()
852{
853        # Number of args to shift, 255..255, first non-255 byte, zeroes
854        set -- $[ 5 - ($1 / 8) ] 255 255 255 255 $[ (255 << (8 - ($1 % 8))) & 255 ] 0 0 0
855        [ $1 -gt 1 ] && shift $1 || shift
856        echo ${1-0}.${2-0}.${3-0}.${4-0}
857}
858
[07c3a59]859# Obtener los parámetros de red de la interfaz por defecto.
[7586ca3]860function getNetworkSettings()
861{
[d168a46]862        # Arrays globales definidas:
863        # - DEVICE:     nombres de dispositivos de red activos.
864        # - SERVERIP:   IPs locales del servidor.
865        # - NETIP:      IPs de redes.
866        # - NETMASK:    máscaras de red.
867        # - NETBROAD:   IPs de difusión de redes.
868        # - ROUTERIP:   IPs de routers.
869        # Otras variables globales:
870        # - DEFAULTDEV: dispositivo de red por defecto.
871        # - DNSIP:      IP del servidor DNS principal.
872
873        local i=0
874        local dev=""
875
[109e8b2]876        echoAndLog "${FUNCNAME}(): Detecting network parameters."
[d168a46]877        DEVICE=( $(ip -o link show up | awk '!/loopback/ {sub(/:.*/,"",$2); print $2}') )
878        if [ -z "$DEVICE" ]; then
879                errorAndLog "${FUNCNAME}(): Network devices not detected."
[62e3bcf]880                exit 1
881        fi
[d168a46]882        for dev in ${DEVICE[*]}; do
[2c1b0cf]883                SERVERIP[i]=$(ip -o addr show dev "$dev" | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4); exit;}')
[d168a46]884                if [ -n "${SERVERIP[i]}" ]; then
[2c1b0cf]885                        NETMASK[i]=$( cidr2mask $(ip -o addr show dev "$dev" | awk '$3~/inet$/ {sub (/.*\//, "", $4); print ($4); exit;}') )
886                        NETBROAD[i]=$(ip -o addr show dev "$dev" | awk '$3~/inet$/ {print ($6); exit;}')
887                        NETIP[i]=$(ip route list proto kernel | awk -v d="$dev" '$3==d && /src/ {sub (/\/.*/,""); print $1; exit;}')
888                        ROUTERIP[i]=$(ip route list default | awk -v d="$dev" '$5==d {print $3; exit;}')
[d168a46]889                        DEFAULTDEV=${DEFAULTDEV:-"$dev"}
890                fi
[ce85ae8]891                let i++
[d168a46]892        done
[2c1b0cf]893        DNSIP=$(systemd-resolve --status 2>/dev/null | awk '/DNS Servers:/ {print $3; exit;}')
894        [ -z "$DNSIP" ] && DNSIP=$(awk '/nameserver/ {print $2; exit;}' /etc/resolv.conf)
[03cfd6e]895        if [ -z "${NETIP[*]}" -o -z "${NETMASK[*]}" ]; then
[62e3bcf]896                errorAndLog "${FUNCNAME}(): Network not detected."
[7586ca3]897                exit 1
898        fi
[cc7eab7]899
900        # Variables de ejecución de Apache
901        # - APACHE_RUN_USER
902        # - APACHE_RUN_GROUP
[d168a46]903        if [ -f $APACHECFGDIR/envvars ]; then
904                source $APACHECFGDIR/envvars
[cc7eab7]905        fi
[d168a46]906        APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
907        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
[73a1bd6]908
909        echoAndLog "${FUNCNAME}(): Default network device: $DEFAULTDEV."
[7586ca3]910}
911
912
913############################################################
[892606b9]914### Esqueleto para el Servicio pxe y contenedor tftpboot ###
915############################################################
916
[e0edc14]917function tftpConfigure()
918{
[109e8b2]919        echoAndLog "${FUNCNAME}(): Configuring TFTP service."
920        # Habilitar TFTP y reiniciar Inetd.
[8244351]921        if [ -n "$TFTPSERV" ]; then
[584b103]922                if [ -f $INETDCFGDIR/$TFTPSERV ]; then
923                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/$TFTPSERV
924                else
925                        service=$TFTPSERV
[b8969db]926                        $ENABLESERVICE; $STARTSERVICE
[584b103]927                fi
[8244351]928        fi
[53fba30]929        service=$INETDSERV
930        $ENABLESERVICE; $STARTSERVICE
[892606b9]931
[297df16]932        # comprobamos el servicio tftp
933        sleep 1
934        testPxe
[892606b9]935}
936
[0a735488]937# Comprueba que haya conexión al servicio TFTP/PXE.
[e0edc14]938function testPxe ()
939{
[297df16]940        echoAndLog "${FUNCNAME}(): Checking TFTP service... please wait."
[beaebf8]941        echo "test" >$TFTPCFGDIR/testpxe
942        tftp -v 127.0.0.1 -c get testpxe /tmp/testpxe && echoAndLog "TFTP service is OK." || errorAndLog "TFTP service is down."
943        rm -f $TFTPCFGDIR/testpxe /tmp/testpxe
[e4b1572]944}
945
946
947########################################################################
[5f21d34]948## Configuración servicio Samba
[8fc9552]949########################################################################
[e4b1572]950
951# Configurar servicios Samba.
[8fc9552]952function smbConfigure()
953{
[e0edc14]954        echoAndLog "${FUNCNAME}(): Configuring Samba service."
[8fc9552]955
[d168a46]956        backupFile $SAMBACFGDIR/smb.conf
[8fc9552]957       
[5f21d34]958        # Copiar plantailla de recursos para OpenGnsys
[c1e00e4]959        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
[d168a46]960                $WORKDIR/opengnsys/server/etc/smb-og.conf.tmpl > $SAMBACFGDIR/smb-og.conf
[813f617]961        # Configurar y recargar Samba"
[5f21d34]962        perl -pi -e "s/WORKGROUP/OPENGNSYS/; s/server string \=.*/server string \= OpenGnsys Samba Server/" $SAMBACFGDIR/smb.conf
[03cfd6e]963        if ! grep -q "smb-og" $SAMBACFGDIR/smb.conf; then
964                echo "include = $SAMBACFGDIR/smb-og.conf" >> $SAMBACFGDIR/smb.conf
965        fi
[53fba30]966        service=$SAMBASERV
967        $ENABLESERVICE; $STARTSERVICE
[8fc9552]968        if [ $? -ne 0 ]; then
[813f617]969                errorAndLog "${FUNCNAME}(): error while configure Samba"
[8fc9552]970                return 1
971        fi
[eb9424f]972        # Crear clave para usuario de acceso a los recursos.
[813f617]973        echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | smbpasswd -a -s $OPENGNSYS_CLIENT_USER
[8fc9552]974
[813f617]975        echoAndLog "${FUNCNAME}(): Added Samba configuration."
[8fc9552]976        return 0
977}
978
979
[b6906f7]980########################################################################
[5f21d34]981## Configuración servicio Rsync
[e70925a]982########################################################################
983
984# Configurar servicio Rsync.
985function rsyncConfigure()
986{
987        echoAndLog "${FUNCNAME}(): Configuring Rsync service."
988
989        backupFile $RSYNCCFGDIR/rsyncd.conf
990
991        # Configurar acceso a Rsync.
992        sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENT_USER/g" \
993                $WORKDIR/opengnsys/repoman/etc/rsyncd.conf.tmpl > $RSYNCCFGDIR/rsyncd.conf
994        # Habilitar Rsync y reiniciar Inetd.
995        if [ -n "$RSYNCSERV" ]; then
[4666588]996                if [ -f /etc/default/rsync ]; then
997                        perl -pi -e 's/RSYNC_ENABLE=.*/RSYNC_ENABLE=inetd/' /etc/default/rsync
998                fi
[f243a47]999                if [ -f $INETDCFGDIR/rsync ]; then
1000                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/rsync
1001                else
1002                        cat << EOT > $INETDCFGDIR/rsync
1003service rsync
1004{
1005        disable = no
1006        socket_type = stream
1007        wait = no
1008        user = root
1009        server = $(which rsync)
1010        server_args = --daemon
1011        log_on_failure += USERID
1012        flags = IPv6
1013}
1014EOT
1015                fi
[e70925a]1016                service=$RSYNCSERV $ENABLESERVICE
1017                service=$INETDSERV $STARTSERVICE
1018        fi
1019
1020        echoAndLog "${FUNCNAME}(): Added Rsync configuration."
1021        return 0
1022}
1023
1024       
1025########################################################################
[5f21d34]1026## Configuración servicio DHCP
[b6906f7]1027########################################################################
1028
[e4b1572]1029# Configurar servicios DHCP.
[7586ca3]1030function dhcpConfigure()
1031{
[836a7597]1032        echoAndLog "${FUNCNAME}(): Sample DHCP configuration."
[a555f49]1033
[d168a46]1034        local errcode=0
1035        local i=0
1036        local dev=""
1037
1038        backupFile $DHCPCFGDIR/dhcpd.conf
1039        for dev in ${DEVICE[*]}; do
[01a9904]1040                if [ -n "${SERVERIP[i]}" ]; then
[d168a46]1041                        backupFile $DHCPCFGDIR/dhcpd-$dev.conf
[e4b1572]1042                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1043                            -e "s/NETIP/${NETIP[i]}/g" \
1044                            -e "s/NETMASK/${NETMASK[i]}/g" \
1045                            -e "s/NETBROAD/${NETBROAD[i]}/g" \
1046                            -e "s/ROUTERIP/${ROUTERIP[i]}/g" \
[d168a46]1047                            -e "s/DNSIP/$DNSIP/g" \
1048                            $WORKDIR/opengnsys/server/etc/dhcpd.conf.tmpl > $DHCPCFGDIR/dhcpd-$dev.conf || errcode=1
1049                fi
1050                let i++
1051        done
1052        if [ $errcode -ne 0 ]; then
[b25fc47]1053                errorAndLog "${FUNCNAME}(): error while configuring DHCP server"
[a555f49]1054                return 1
1055        fi
[d168a46]1056        ln -f $DHCPCFGDIR/dhcpd-$DEFAULTDEV.conf $DHCPCFGDIR/dhcpd.conf
[53fba30]1057        service=$DHCPSERV
1058        $ENABLESERVICE; $STARTSERVICE
[d168a46]1059        echoAndLog "${FUNCNAME}(): Sample DHCP configured in \"$DHCPCFGDIR\"."
[a555f49]1060        return 0
[892606b9]1061}
1062
1063
[a01156a]1064#####################################################################
1065####### Funciones específicas de la instalación de Opengnsys
1066#####################################################################
1067
[5f21d34]1068# Copiar ficheros del OpenGnsys Web Console.
[7586ca3]1069function installWebFiles()
1070{
[2b793a8]1071        local COMPATDIR f
[7829e4e]1072        local SLIMFILE="slim-2.6.1.zip"
[8b8e948]1073        local SWAGGERFILE="swagger-ui-2.2.5.zip"
[2b793a8]1074
[dce072b]1075        echoAndLog "${FUNCNAME}(): Installing web files..."
[2b793a8]1076        # Copiar ficheros.
1077        cp -a $WORKDIR/opengnsys/admin/WebConsole/* $INSTALL_TARGET/www   #*/ comentario para Doxygen.
[7586ca3]1078        if [ $? != 0 ]; then
[dce072b]1079                errorAndLog "${FUNCNAME}(): Error copying web files."
[7586ca3]1080                exit 1
1081        fi
[7829e4e]1082
[1635f45]1083        # Descomprimir librerías: Slim y Swagger-UI.
[7829e4e]1084        unzip -o $WORKDIR/opengnsys/admin/$SLIMFILE -d $INSTALL_TARGET/www/rest
[8b8e948]1085        unzip -o $WORKDIR/opengnsys/admin/$SWAGGERFILE -d $INSTALL_TARGET/www/rest
[7829e4e]1086
[2b793a8]1087        # Compatibilidad con dispositivos móviles.
1088        COMPATDIR="$INSTALL_TARGET/www/principal"
1089        for f in acciones administracion aula aulas hardwares imagenes menus repositorios softwares; do
1090                sed 's/clickcontextualnodo/clicksupnodo/g' $COMPATDIR/$f.php > $COMPATDIR/$f.device.php
1091        done
1092        cp -a $COMPATDIR/imagenes.device.php $COMPATDIR/imagenes.device4.php
[aafe8f9]1093        # Acceso al manual de usuario
1094        ln -fs ../doc/userManual $INSTALL_TARGET/www/userManual
[0645906]1095        # Ficheros de log de la API REST.
1096        touch $INSTALL_TARGET/log/{ogagent,remotepc,rest}.log
[2b793a8]1097
[dce072b]1098        echoAndLog "${FUNCNAME}(): Web files installed successfully."
[7586ca3]1099}
1100
[ec045b1]1101# Copiar ficheros en la zona de descargas de OpenGnsys Web Console.
1102function installDownloadableFiles()
1103{
[1de0d12d]1104        local VERSIONFILE OGVERSION FILENAME TARGETFILE
1105
1106        # Obtener versión a descargar.
1107        VERSIONFILE="$INSTALL_TARGET/doc/VERSION.json"
1108        OGVERSION="$(jq -r ".ogagent // \"$INSTVERSION\"" $VERSIONFILE 2>/dev/null || echo "$INSTVERSION")"
1109        FILENAME="ogagentpkgs-$OGVERSION.tar.gz"
1110        TARGETFILE=$WORKDIR/$FILENAME
1111
[ec045b1]1112        # Descargar archivo comprimido, si es necesario.
1113        if [ -s $PROGRAMDIR/$FILENAME ]; then
1114                echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
1115                mv $PROGRAMDIR/$FILENAME $TARGETFILE
1116        else
1117                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
[d5cbfa8]1118                curl $DOWNLOADURL/$FILENAME -o $TARGETFILE
[ec045b1]1119        fi
1120        if [ ! -s $TARGETFILE ]; then
1121                errorAndLog "${FUNCNAME}(): Cannot download $FILENAME"
1122                return 1
1123        fi
1124       
1125        # Descomprimir fichero en zona de descargas.
1126        tar xvzf $TARGETFILE -C $INSTALL_TARGET/www/descargas
1127        if [ $? != 0 ]; then
1128                errorAndLog "${FUNCNAME}(): Error uncompressing archive."
1129                exit 1
1130        fi
1131}
1132
[7586ca3]1133# Configuración específica de Apache.
[73a1bd6]1134function installWebConsoleApacheConf()
[a01156a]1135{
1136        if [ $# -ne 2 ]; then
[dce072b]1137                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]1138                exit 1
1139        fi
1140
[f9e3393]1141        local path_opengnsys_base="$1"
1142        local path_apache2_confd="$2"
[30837bb]1143        local CONSOLEDIR=${path_opengnsys_base}/www
[9215580]1144        local sockfile
[a01156a]1145
[892606b9]1146        if [ ! -d $path_apache2_confd ]; then
[dce072b]1147                errorAndLog "${FUNCNAME}(): path to apache2 conf.d can not found, verify your server installation"
[892606b9]1148                return 1
1149        fi
1150
[7586ca3]1151        mkdir -p $path_apache2_confd/{sites-available,sites-enabled}
[892606b9]1152
[dce072b]1153        echoAndLog "${FUNCNAME}(): creating apache2 config file.."
[a01156a]1154
[9215580]1155        # Avtivar PHP-FPM.
1156        echoAndLog "${FUNCNAME}(): configuring PHP-FPM"
1157        service=$PHPFPMSERV
1158        $ENABLESERVICE; $STARTSERVICE
[e432478]1159        sockfile=$(find /run/php -name "php*.sock" -type s -print 2>/dev/null | tail -1)
[9215580]1160
1161        # Activar módulos de Apache.
1162        $APACHEENABLEMODS
[3ce53a7]1163        # Activar HTTPS.
[643ca8c]1164        $APACHEENABLESSL
1165        $APACHEMAKECERT
[30837bb]1166        # Genera configuración de consola web a partir del fichero plantilla.
[f9e3393]1167        if [ -n "$(apachectl -v | grep "2\.[0-2]")" ]; then
1168                # Configuración para versiones anteriores de Apache.
[6f4d39b]1169                sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
[f3dde7e]1170                        $WORKDIR/opengnsys/server/etc/apache-prev2.4.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}
[f9e3393]1171        else
1172                # Configuración específica a partir de Apache 2.4
[37481d8]1173                if [ -n "$sockfile" ]; then
1174                        sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
1175                            -e "s,proxy:fcgi:.*,proxy:unix:${sockfile%% *}|fcgi://localhost\",g" \
1176                                $WORKDIR/opengnsys/server/etc/apache.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf
1177                else
1178                        sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
1179                                $WORKDIR/opengnsys/server/etc/apache.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf
1180                fi
[f9e3393]1181        fi
[643ca8c]1182        $APACHEENABLEOG
[a01156a]1183        if [ $? -ne 0 ]; then
[dce072b]1184                errorAndLog "${FUNCNAME}(): config file can't be linked to apache conf, verify your server installation"
[a01156a]1185                return 1
1186        fi
[103bc82]1187        echoAndLog "${FUNCNAME}(): config file created and linked, restarting apache daemon"
1188        service=$APACHESERV
1189        $ENABLESERVICE; $STARTSERVICE
1190        return 0
[a01156a]1191}
1192
[8fc9552]1193
[5d6bf97]1194# Crear documentación Doxygen para la consola web.
1195function makeDoxygenFiles()
1196{
1197        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
1198        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
1199                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
1200        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
1201                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
[ead38fb]1202                return 1
[5d6bf97]1203        fi
1204        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
1205        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
1206}
1207
1208
[a01156a]1209# Crea la estructura base de la instalación de opengnsys
[eb9424f]1210function createDirs()
[a01156a]1211{
1212        if [ $# -ne 1 ]; then
[dce072b]1213                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]1214                exit 1
1215        fi
1216
[eb9424f]1217        local path_opengnsys_base="$1"
[a01156a]1218
[eb9424f]1219        # Crear estructura de directorios.
[dce072b]1220        echoAndLog "${FUNCNAME}(): creating directory paths in $path_opengnsys_base"
[a01156a]1221        mkdir -p $path_opengnsys_base
1222        mkdir -p $path_opengnsys_base/bin
[d47ec6c]1223        mkdir -p $path_opengnsys_base/client/{cache,images,log}
[49c6891]1224        mkdir -p $path_opengnsys_base/doc
[5c33840]1225        mkdir -p $path_opengnsys_base/etc
[a01156a]1226        mkdir -p $path_opengnsys_base/lib
[1cc5697]1227        mkdir -p $path_opengnsys_base/log/clients
[eb9424f]1228        ln -fs $path_opengnsys_base/log /var/log/opengnsys
[7586ca3]1229        mkdir -p $path_opengnsys_base/sbin
[a01156a]1230        mkdir -p $path_opengnsys_base/www
[d7ece95]1231        mkdir -p $path_opengnsys_base/images/groups
[87c7b02]1232        mkdir -p $TFTPCFGDIR
[63fd1ba]1233        ln -fs $TFTPCFGDIR $path_opengnsys_base/tftpboot
[c30c33e]1234        mkdir -p $path_opengnsys_base/tftpboot/{menu.lst,grub}
[a01156a]1235        if [ $? -ne 0 ]; then
[dce072b]1236                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
[a01156a]1237                return 1
1238        fi
1239
[eb9424f]1240        # Crear usuario ficticio.
1241        if id -u $OPENGNSYS_CLIENT_USER &>/dev/null; then
1242                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENT_USER\" is already created"
1243        else
[5f21d34]1244                echoAndLog "${FUNCNAME}(): creating OpenGnsys user"
[eb9424f]1245                useradd $OPENGNSYS_CLIENT_USER 2>/dev/null
1246                if [ $? -ne 0 ]; then
[5f21d34]1247                        errorAndLog "${FUNCNAME}(): error creating OpenGnsys user"
[eb9424f]1248                        return 1
1249                fi
1250        fi
1251
[7669bca]1252        # Mover el fichero de registro de instalación al directorio de logs.
[acfb07d]1253        echoAndLog "${FUNCNAME}(): moving installation log file"
1254        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
[7669bca]1255        chmod 600 $LOG_FILE
[acfb07d]1256
[dce072b]1257        echoAndLog "${FUNCNAME}(): directory paths created"
[a01156a]1258        return 0
1259}
1260
[463a1d49]1261# Copia ficheros de configuración y ejecutables genéricos del servidor.
[73a1bd6]1262function copyServerFiles ()
[e0edc14]1263{
[463a1d49]1264        if [ $# -ne 1 ]; then
[879689f]1265                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[463a1d49]1266                exit 1
1267        fi
1268
[7caf5a7c]1269        local path_opengnsys_base="$1"
[463a1d49]1270
[a43e90d]1271        # Lista de ficheros y directorios origen y de directorios destino.
[cfad47b]1272        local SOURCES=( server/tftpboot \
[98dedfc]1273                        /usr/lib/shim/shimx64.efi.signed \
[c30c33e]1274                        /usr/lib/grub/x86_64-efi-signed/grubnetx64.efi.signed \
[7caf5a7c]1275                        server/bin \
1276                        repoman/bin \
[3e7d77b]1277                        server/lib \
[42a0e41]1278                        admin/Sources/Services/ogAdmRepoAux
[7caf5a7c]1279                        installer/opengnsys_uninstall.sh \
1280                        installer/opengnsys_update.sh \
[6777e3e]1281                        installer/opengnsys_export.sh \
1282                        installer/opengnsys_import.sh \
[7caf5a7c]1283                        doc )
[cfad47b]1284        local TARGETS=( tftpboot \
[c30c33e]1285                        tftpboot \
[98dedfc]1286                        tftpboot/grubx64.efi \
[7caf5a7c]1287                        bin \
1288                        bin \
[3e7d77b]1289                        lib \
[42a0e41]1290                        sbin \
[7caf5a7c]1291                        lib \
1292                        lib \
[6777e3e]1293                        lib \
1294                        lib \
[7caf5a7c]1295                        doc )
[463a1d49]1296
1297        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
[879689f]1298                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
[463a1d49]1299                exit 1
1300        fi
1301
[a43e90d]1302        # Copiar ficheros.
[879689f]1303        echoAndLog "${FUNCNAME}(): copying files to server directories"
[f2bb433]1304
[8457092]1305        pushd $WORKDIR/opengnsys
[463a1d49]1306        local i
1307        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
1308                if [ -f "${SOURCES[$i]}" ]; then
[879689f]1309                        echoAndLog "Copying ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
[b5aae72]1310                        cp -a "${SOURCES[$i]}" "${path_opengnsys_base}/${TARGETS[$i]}"
[8457092]1311                elif [ -d "${SOURCES[$i]}" ]; then
[879689f]1312                        echoAndLog "Copying content of ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
[8457092]1313                        cp -a "${SOURCES[$i]}"/* "${path_opengnsys_base}/${TARGETS[$i]}"
[98dedfc]1314                else
[346eaee]1315                        warningAndLog "Unable to copy ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
[463a1d49]1316                fi
1317        done
[a43e90d]1318
[7586ca3]1319        popd
[892606b9]1320}
1321
[7586ca3]1322####################################################################
[5eb61a6]1323### Funciones de compilación de código fuente de servicios
[7586ca3]1324####################################################################
1325
[5f21d34]1326# Compilar los servicios de OpenGnsys
[c070d3d]1327function ogServerCompilation ()
[7586ca3]1328{
[c070d3d]1329        local ogserverUrl="https://codeload.github.com/opengnsys/ogServer/zip/$BRANCH"
1330        local error=0
1331
1332        echoAndLog "${FUNCNAME}(): downloading ogServer code..."
[0795938]1333
[c070d3d]1334        if ! (curl "${ogserverUrl}" -o ogserver.zip && \
1335              unzip -qo "ogserver.zip")
1336        then
1337                errorAndLog "${FUNCNAME}(): "\
1338                            "error getting ogServer code from ${ogserverUrl}"
1339                return 1
1340        fi
1341        rm -f ogserver.zip
1342        echoAndLog "${FUNCNAME}(): ogServer code was downloaded"
1343
1344        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Server"
1345        pushd "$WORKDIR/ogServer-$BRANCH"
[c583144]1346        autoreconf -fi && ./configure && make && mv ogserver $INSTALL_TARGET/sbin
[13a01a7]1347        if [ $? -ne 0 ]; then
[c070d3d]1348                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Server"
1349                error=1
[13a01a7]1350        fi
[7586ca3]1351        popd
[13a01a7]1352
[c070d3d]1353        return $error
[b6906f7]1354}
1355
[7b61735]1356####################################################################
1357### Funciones de copia de la Interface de administración
1358####################################################################
1359
1360# Copiar carpeta de Interface
[c1e00e4]1361function copyInterfaceAdm ()
[7b61735]1362{
1363        local hayErrores=0
1364       
[fbd9bcc]1365        # Crear carpeta y copiar Interface
[7b61735]1366        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
[fbd9bcc]1367        cp -ar $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client/interfaceAdm
[7b61735]1368        if [ $? -ne 0 ]; then
1369                echoAndLog "${FUNCNAME}(): error while copying Administration Interface Folder"
1370                hayErrores=1
1371        fi
1372
1373        return $hayErrores
1374}
[b6906f7]1375
[5050850]1376
[892606b9]1377####################################################################
1378### Funciones instalacion cliente opengnsys
1379####################################################################
1380
[73a1bd6]1381function copyClientFiles()
[7586ca3]1382{
[d168a46]1383        local errstatus=0
[a555f49]1384
[5f21d34]1385        echoAndLog "${FUNCNAME}(): Copying OpenGnsys Client files."
[73a1bd6]1386        cp -a $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
[d47d38d]1387        if [ $? -ne 0 ]; then
[9ef8920]1388                errorAndLog "${FUNCNAME}(): error while copying client estructure"
[d168a46]1389                errstatus=1
[9ef8920]1390        fi
1391       
[5f21d34]1392        echoAndLog "${FUNCNAME}(): Copying OpenGnsys Cloning Engine files."
[d47d38d]1393        mkdir -p $INSTALL_TARGET/client/lib/engine/bin
[73a1bd6]1394        cp -a $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
[a555f49]1395        if [ $? -ne 0 ]; then
1396                errorAndLog "${FUNCNAME}(): error while copying engine files"
[d168a46]1397                errstatus=1
[a555f49]1398        fi
[9ef8920]1399       
[d168a46]1400        if [ $errstatus -eq 0 ]; then
[9ef8920]1401                echoAndLog "${FUNCNAME}(): client copy files success."
1402        else
1403                errorAndLog "${FUNCNAME}(): client copy files with errors"
1404        fi
1405
[53c927c]1406        local ogclientUrl="https://codeload.github.com/opengnsys/ogClient/zip/$BRANCH"
[51ce65c]1407
1408        echoAndLog "${FUNCNAME}(): downloading ogClient code..."
1409
1410        if ! (curl "${ogclientUrl}" -o ogclient.zip && \
1411             unzip -qo ogclient.zip && \
1412             mv "ogClient-$BRANCH" $INSTALL_TARGET/client/ogClient)
1413        then
1414                errorAndLog "${FUNCNAME}(): "\
1415                            "error getting ogClient code from ${ogclientUrl}"
1416                return 1
1417        fi
1418        rm -f ogclient.zip
1419        echoAndLog "${FUNCNAME}(): ogClient code was downloaded"
1420
[d168a46]1421        return $errstatus
[463a1d49]1422}
1423
1424
[5050850]1425# Crear certificados para la firma de cargadores de arranque.
1426function createCerts ()
1427{
1428        local SSLCFGDIR=$INSTALL_TARGET/client/etc/ssl
1429        echoAndLog "${FUNCNAME}(): creating certificate files"
1430        mkdir -p $SSLCFGDIR/{certs,private}
1431        openssl req -new -x509 -newkey rsa:2048 -keyout $SSLCFGDIR/private/opengnsys.key -out $SSLCFGDIR/certs/opengnsys.crt -nodes -days 3650 -subj "/CN=OpenGnsys/"
1432        openssl x509 -in $SSLCFGDIR/certs/opengnsys.crt -out $SSLCFGDIR/certs/opengnsys.cer -outform DER
1433        echoAndLog "${FUNCNAME}(): certificate successfully created"
1434}
1435
1436
[5f21d34]1437# Crear cliente OpenGnsys.
[5ad5dcc]1438function clientCreate()
[813f617]1439{
[6019b12]1440        if [ $# -ne 1 ]; then
1441                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1442                exit 1
1443        fi
1444
1445        local FILENAME="$1"
[0b85cc93]1446        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
[d168a46]1447 
[79c26a8]1448        # Descargar cliente, si es necesario.
1449        if [ -s $PROGRAMDIR/$FILENAME ]; then
1450                echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
1451                mv $PROGRAMDIR/$FILENAME $TARGETFILE
1452        else
[ec045b1]1453                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
[6019b12]1454                oglivecli download $FILENAME
[79c26a8]1455        fi
[0b85cc93]1456        if [ ! -s $TARGETFILE ]; then
[ec045b1]1457                errorAndLog "${FUNCNAME}(): Error loading $FILENAME"
[813f617]1458                return 1
1459        fi
[1893b9d]1460
[79c26a8]1461        # Montar imagen, copiar cliente ogclient y desmontar.
[0496417]1462        echoAndLog "${FUNCNAME}(): Installing ogLive Client"
[6ef01d9]1463        echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | \
[6019b12]1464                        oglivecli install $FILENAME
[6ef01d9]1465
[813f617]1466        echoAndLog "${FUNCNAME}(): Client generation success"
1467}
1468
1469
[5f21d34]1470# Configuración básica de servicios de OpenGnsys
[cc7eab7]1471function openGnsysConfigure()
1472{
[d168a46]1473        local i=0
1474        local dev=""
[7d4ce64]1475        local CONSOLEURL
[d168a46]1476
[9ee62ad]1477        echoAndLog "${FUNCNAME}(): Copying init files."
[42a0e41]1478        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
[9da3f87]1479        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.service \
1480              /lib/systemd/system/opengnsys.service
[f6e87d3]1481        cp -a $WORKDIR/ogServer-$BRANCH/cfg/ogserver.service \
1482              /lib/systemd/system/ogserver.service
[42a0e41]1483        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default /etc/default/opengnsys
[b8969db]1484        # Deshabilitar servicios de BitTorrent si no están instalados.
1485        if [ ! -e /usr/bin/bttrack ]; then
[fdab5d0]1486                sed -i 's/RUN_BTTRACKER="yes"/RUN_BTTRACKER="no"/; s/RUN_BTSEEDER="yes"/RUN_BTSEEDER="no"/' \
[b8969db]1487                        /etc/default/opengnsys
1488        fi
[9ee62ad]1489        echoAndLog "${FUNCNAME}(): Creating cron files."
1490        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
[8fc9552]1491        echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
[dc762088]1492        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
[0645906]1493        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/ogagentqueue.cron ] && $INSTALL_TARGET/bin/ogagentqueue.cron" > /etc/cron.d/ogagentqueue
[d168a46]1494
[1be256f]1495        echoAndLog "${FUNCNAME}(): Creating logrotate configuration files."
[700299b]1496        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
[1be256f]1497                $WORKDIR/opengnsys/server/etc/logrotate.tmpl > /etc/logrotate.d/opengnsysServer
1498
1499        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1500                $WORKDIR/opengnsys/repoman/etc/logrotate.tmpl > /etc/logrotate.d/opengnsysRepo
[700299b]1501
[5f21d34]1502        echoAndLog "${FUNCNAME}(): Creating OpenGnsys config files."
[d168a46]1503        for dev in ${DEVICE[*]}; do
1504                if [ -n "${SERVERIP[i]}" ]; then
[5cbc75b]1505                        echo "{
1506                                \"rest\" : {
1507                                        \"ip\" : \"${SERVERIP[i]}\",
1508                                        \"port\" : \"8888\",
1509                                        \"api_token\": \"5a5ca1172136299640a9f47469237e0a\"
1510                                },
1511                                \"database\" : {
1512                                        \"ip\": \"127.0.0.1\",
1513                                        \"port\": \"3306\",
1514                                        \"name\" : \"$OPENGNSYS_DATABASE\",
1515                                        \"user\" : \"$OPENGNSYS_DB_USER\",
1516                                        \"pass\" : \"$OPENGNSYS_DB_PASSWD\"
1517                                },
1518                                \"wol\" : {
1519                                        \"interface\" : \"$dev\"
1520                                }
1521                        }" | jq '.' > "$INSTALL_TARGET"/etc/ogserver-"$dev".json
[d168a46]1522                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
[b351d8a]1523                                $WORKDIR/opengnsys/repoman/etc/ogAdmRepo.cfg.tmpl > $INSTALL_TARGET/etc/ogAdmRepo-$dev.cfg
[1a2fa9d8]1524                        CONSOLEURL="https://${SERVERIP[i]}/opengnsys"
[d168a46]1525                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1526                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1527                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1528                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
[b22305e]1529                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
[d168a46]1530                                $INSTALL_TARGET/www/controlacceso.php > $INSTALL_TARGET/www/controlacceso-$dev.php
[7d4ce64]1531                        if [ "$dev" == "$DEFAULTDEV" ]; then
[1a2fa9d8]1532                                OPENGNSYS_CONSOLEURL="$CONSOLEURL"
[51ce65c]1533                                OPENGNSYS_SERVERIP="${SERVERIP[i]}"
[7d4ce64]1534                        fi
[d168a46]1535                fi
1536                let i++
1537        done
[5cbc75b]1538        ln -f $INSTALL_TARGET/etc/ogserver-$DEFAULTDEV.json $INSTALL_TARGET/etc/ogserver.json
[d168a46]1539        ln -f $INSTALL_TARGET/etc/ogAdmRepo-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmRepo.cfg
1540        ln -f $INSTALL_TARGET/www/controlacceso-$DEFAULTDEV.php $INSTALL_TARGET/www/controlacceso.php
[1f7b2d0]1541
[a3855dc]1542        # Configuración del motor de clonación.
1543        # - Zona horaria del servidor.
1544        TZ=$(timedatectl status|awk -F"[:()]" '/Time.*zone/ {print $2}')
1545        cat << EOT >> $INSTALL_TARGET/client/etc/engine.cfg
1546# OpenGnsys Server timezone.
1547TZ="${TZ// /}"
1548EOT
1549
[1f7b2d0]1550        # Revisar permisos generales.
1551        if [ -x $INSTALL_TARGET/bin/checkperms ]; then
1552                echoAndLog "${FUNCNAME}(): Checking permissions."
[6019b12]1553                OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENT_USER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" checkperms
[1f7b2d0]1554        fi
1555
[4e19f13]1556        # Evitar inicio de duplicado en Ubuntu 14.04 (Upstart y SysV Init).
[c7ade22]1557        if [ -f /etc/init/${MYSQLSERV}.conf -a -n "$(which initctl 2>/dev/null)" ]; then
[4e19f13]1558                service=$MYSQLSERV
1559                $DISABLESERVICE
1560        fi
1561
[dde2db1]1562        # Actualizar tokens de autenticación e iniciar los servicios.
[53fba30]1563        service="opengnsys"
[dde2db1]1564        $ENABLESERVICE
1565        if [ -x $INSTALL_TARGET/bin/settoken ]; then
1566                echoAndLog "${FUNCNAME}(): Setting authentication tokens and starting OpenGnsys services."
[afd6b4e]1567                $INSTALL_TARGET/bin/settoken "$OPENGNSYS_DB_USER"
[dde2db1]1568                $INSTALL_TARGET/bin/settoken -f
1569        else
1570                echoAndLog "${FUNCNAME}(): Starting OpenGnsys services."
1571                $STARTSERVICE
1572        fi
[51ce65c]1573
[f6e87d3]1574        # Enable and start ogServer systemd service
1575        service="ogserver"
1576        $ENABLESERVICE; $STARTSERVICE
1577
[51ce65c]1578        echoAndLog "${FUNCNAME}(): Creating ogClient config files."
1579        sed -i -e "s/127\.0\.0\.1/$OPENGNSYS_SERVERIP/g" \
[41f8ff6]1580            $INSTALL_TARGET/client/ogClient/cfg/ogclient.json
[cc7eab7]1581}
1582
[b6906f7]1583
[a01156a]1584#####################################################################
[180a07dd]1585#######  Función de resumen informativo de la instalación
1586#####################################################################
1587
[813f617]1588function installationSummary()
1589{
[832e27b]1590        local VERSIONFILE REVISION
1591
[eb9424f]1592        # Crear fichero de versión y revisión, si no existe.
[3bbaf79]1593        VERSIONFILE="$INSTALL_TARGET/doc/VERSION.json"
1594        [ -f $VERSIONFILE ] || echo '{ "project": "OpenGnsys" }' >$VERSIONFILE
1595        # Incluir datos de revisión, si se está instalando desde el repositorio
[130bdbf]1596        # de código o si no está incluida en el fichero de versión.
[3bbaf79]1597        if [ $REMOTE -eq 1 ] || [ -z "$(jq -r '.release' $VERSIONFILE)" ]; then
[832e27b]1598                # Revisión: rAñoMesDía.Gitcommit (8 caracteres de fecha y 7 primeros de commit).
[6ab13a3]1599                RELEASE=$(curl -s "$API_URL/branches/$BRANCH" | jq -r '"r" + (.commit.commit.committer.date | split("-") | join("")[:8]) + "." + (.commit.sha[:7])' 2>/dev/null)
1600                # Obtener revisión para etiqueta de versión en vez de rama de código.
[0be5245]1601                [ -z "$RELEASE" ] && RELEASE=$(curl -s $(curl -s "$API_URL/tags" | jq -r ".[] | select(.name==\"$BRANCH\").commit.url" 2>/dev/null) | jq -r '"r" + (.commit.committer.date | split("-") | join("")[:8]) + "." + .sha[:7]' 2>/dev/null)
[6ab13a3]1602                jq ".release=\"$RELEASE\"" $VERSIONFILE | sponge $VERSIONFILE
[130bdbf]1603        fi
[3bbaf79]1604        VERSION="$(jq -r '[.project, .version, .codename, .release] | join(" ")' $VERSIONFILE 2>/dev/null)"
[eb9424f]1605
1606        # Mostrar información.
[180a07dd]1607        echo
[5f21d34]1608        echoAndLog "OpenGnsys Installation Summary"
[180a07dd]1609        echo       "=============================="
[3bbaf79]1610        echoAndLog "Project version:                  $VERSION"
[49c6891]1611        echoAndLog "Installation directory:           $INSTALL_TARGET"
[acfb07d]1612        echoAndLog "Installation log file:            $LOG_FILE"
[49c6891]1613        echoAndLog "Repository directory:             $INSTALL_TARGET/images"
[d168a46]1614        echoAndLog "DHCP configuration directory:     $DHCPCFGDIR"
[87c7b02]1615        echoAndLog "TFTP configuration directory:     $TFTPCFGDIR"
[dde2db1]1616        echoAndLog "Installed ogLive client:          $(oglivecli list | awk '{print $2}')"
[87c7b02]1617        echoAndLog "Samba configuration directory:    $SAMBACFGDIR"
[49c6891]1618        echoAndLog "Web Console URL:                  $OPENGNSYS_CONSOLEURL"
[6bd2e1e]1619        echoAndLog "Web Console access data:          entered by the user"
[b8969db]1620        if grep -q "^RUN_BTTRACK.*no" /etc/default/opengnsys; then
1621                echoAndLog "BitTorrent service is disabled."
1622        fi
[180a07dd]1623        echo
1624        echoAndLog "Post-Installation Instructions:"
1625        echo       "==============================="
[6bd2e1e]1626        echoAndLog "You can improve server security by configuring firewall and SELinux,"
1627        echoAndLog "   running \"$INSTALL_TARGET/lib/security-config\" script as root."
[4faafcd]1628        echoAndLog "It's strongly recommended to synchronize this server with an NTP server."
[180a07dd]1629        echoAndLog "Review or edit all configuration files."
[c5ce04c]1630        echoAndLog "Insert DHCP configuration data and restart service."
[ce63f8d]1631        echoAndLog "Optional: If you want to use BURG as boot manager, run"
1632        echoAndLog "   \"curl $DOWNLOADURL/burg.tgz -o $INSTALL_TARGET/client/lib/burg.tgz\" as root."
[af5efd6]1633        echoAndLog "Optional: Log-in as Web Console admin user."
1634        echoAndLog " - Review default Organization data and assign access to users."
[180a07dd]1635        echoAndLog "Log-in as Web Console organization user."
[5f21d34]1636        echoAndLog " - Insert OpenGnsys data (labs, computers, menus, etc)."
[180a07dd]1637echo
1638}
1639
1640
1641
1642#####################################################################
[5f21d34]1643####### Proceso de instalación de OpenGnsys
[a01156a]1644#####################################################################
1645
[8ca0cc9]1646# Sólo ejecutable por usuario root
1647if [ "$(whoami)" != 'root' ]; then
1648        echo "ERROR: this program must run under root privileges!!"
1649        exit 1
1650fi
1651
1652globalSetup
[edfcca8]1653# Comprobar instalación previa.
1654if cat $INSTALL_TARGET/doc/VERSION.* &>/dev/null; then
1655        echo "ERROR: OpenGnsys is already installed. Run \"$INSTALL_TARGET/lib/opengnsys_update.sh\" as root to update."
1656        exit 2
1657fi
1658
[5f21d34]1659echoAndLog "OpenGnsys installation begins at $(date)"
[8ca0cc9]1660# Introducir datos de configuración y establecer variables globales.
1661userData
1662
1663mkdir -p $WORKDIR
[6090a2d]1664pushd $WORKDIR
[cc7eab7]1665
[af5efd6]1666# Detectar datos iniciales de auto-configuración del instalador.
[d168a46]1667autoConfigure
1668
1669# Detectar parámetros de red y comprobar si hay conexión.
1670getNetworkSettings
1671if [ $? -ne 0 ]; then
1672        errorAndLog "Error reading default network settings."
1673        exit 1
1674fi
[07c3a59]1675checkNetworkConnection
1676if [ $? -ne 0 ]; then
1677        errorAndLog "Error connecting to server. Causes:"
1678        errorAndLog " - Network is unreachable, review devices parameters."
1679        errorAndLog " - You are inside a private network, configure the proxy service."
1680        errorAndLog " - Server is temporally down, try agian later."
1681        exit 1
1682fi
[7586ca3]1683
[5f21d34]1684# Detener servicios de OpenGnsys, si están activos previamente.
[e0edc14]1685[ -f /etc/init.d/opengnsys ] && /etc/init.d/opengnsys stop
1686
[318efac]1687# Actualizar repositorios
[83518d5]1688updatePackageList
[318efac]1689
[b6906f7]1690# Instalación de dependencias (paquetes de sistema operativo).
[a01156a]1691declare -a notinstalled
1692checkDependencies DEPENDENCIES notinstalled
1693if [ $? -ne 0 ]; then
1694        installDependencies notinstalled
1695        if [ $? -ne 0 ]; then
1696                echoAndLog "Error while installing some dependeces, please verify your server installation before continue"
1697                exit 1
1698        fi
1699fi
[109e8b2]1700if [ -n "$INSTALLEXTRADEPS" ]; then
1701        echoAndLog "Installing extra dependencies"
1702        for (( i=0; i<${#INSTALLEXTRADEPS[*]}; i++ )); do
1703                eval ${INSTALLEXTRADEPS[i]}
1704        done
1705fi     
[a01156a]1706
[ff6c349]1707# Detectar datos de auto-configuración después de instalar paquetes.
1708autoConfigurePost
1709
[5f21d34]1710# Arbol de directorios de OpenGnsys.
[eb9424f]1711createDirs ${INSTALL_TARGET}
[a01156a]1712if [ $? -ne 0 ]; then
1713        errorAndLog "Error while creating directory paths!"
1714        exit 1
1715fi
[b6906f7]1716
[1e7eaab]1717# Si es necesario, descarga el repositorio de código en directorio temporal
[884b6ce]1718if [ $REMOTE -eq 1 ]; then
1719        downloadCode $CODE_URL
[1e7eaab]1720        if [ $? -ne 0 ]; then
[884b6ce]1721                errorAndLog "Error while getting code from the repository"
[1e7eaab]1722                exit 1
1723        fi
1724else
1725        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
[a01156a]1726fi
1727
[5f21d34]1728# Compilar código fuente de los servicios de OpenGnsys.
[c070d3d]1729ogServerCompilation
[13a01a7]1730if [ $? -ne 0 ]; then
1731        errorAndLog "Error while compiling OpenGnsys services"
1732        exit 1
1733fi
[b6906f7]1734
[7b61735]1735# Copiar carpeta Interface entre administración y motor de clonación.
[c1e00e4]1736copyInterfaceAdm
[7b61735]1737if [ $? -ne 0 ]; then
[c1e00e4]1738        errorAndLog "Error while copying Administration Interface"
[7b61735]1739        exit 1
1740fi
1741
[e70925a]1742# Configuración de TFTP.
[318efac]1743tftpConfigure
[b6906f7]1744
[e70925a]1745# Configuración de Samba.
[8fc9552]1746smbConfigure
1747if [ $? -ne 0 ]; then
[c1e00e4]1748        errorAndLog "Error while configuring Samba server!"
[8fc9552]1749        exit 1
1750fi
1751
[e70925a]1752# Configuración de Rsync.
1753rsyncConfigure
1754
1755# Configuración ejemplo DHCP.
[b6906f7]1756dhcpConfigure
[a555f49]1757if [ $? -ne 0 ]; then
1758        errorAndLog "Error while copying your dhcp server files!"
1759        exit 1
1760fi
[b6906f7]1761
[5f21d34]1762# Copiar ficheros de servicios OpenGnsys Server.
[73a1bd6]1763copyServerFiles ${INSTALL_TARGET}
[463a1d49]1764if [ $? -ne 0 ]; then
1765        errorAndLog "Error while copying the server files!"
1766        exit 1
1767fi
[9815cac]1768INSTVERSION=$(jq -r '.version' $INSTALL_TARGET/doc/VERSION.json)
[463a1d49]1769
[5f21d34]1770# Instalar base de datos de OpenGnsys Admin.
[5cc52295]1771isInArray notinstalled "mysql-server" || isInArray notinstalled "mariadb-server"
[b6906f7]1772if [ $? -eq 0 ]; then
[f838845]1773        # Enable database manager (MySQL, if missing, MariaDB).
1774        service=$MYSQLSERV
1775        $ENABLESERVICE
1776        if [ $? != 0 ]; then
1777                service=$MARIADBSERV
1778                $ENABLESERVICE
1779        fi
1780        # Start database manager.
1781        $STARTSERVICE
[094ac0d]1782        # Asignar clave del usuario "root".
[09bf701]1783        mysqlSetRootPassword "${MYSQL_ROOT_PASSWORD}"
[b6906f7]1784else
[094ac0d]1785        # Si ya está instalado el gestor de bases de datos, obtener clave de "root",
[b6906f7]1786        mysqlGetRootPassword
1787fi
[463a1d49]1788
[930563c]1789# Copy MySQL configuration template
1790cp $WORKDIR/opengnsys/server/etc/mysqld-og.cnf $MYSQLCFGDIR 2>/dev/null
[f838845]1791# Restart database manager.
[930563c]1792$STARTSERVICE
1793
[09bf701]1794mysqlTestConnection "${MYSQL_ROOT_PASSWORD}"
[a01156a]1795if [ $? -ne 0 ]; then
1796        errorAndLog "Error while connection to mysql"
1797        exit 1
1798fi
[09bf701]1799mysqlDbExists ${OPENGNSYS_DATABASE}
[a01156a]1800if [ $? -ne 0 ]; then
[cc7eab7]1801        echoAndLog "Creating Web Console database"
[09bf701]1802        mysqlCreateDb ${OPENGNSYS_DATABASE}
[a01156a]1803        if [ $? -ne 0 ]; then
[cc7eab7]1804                errorAndLog "Error while creating Web Console database"
[a01156a]1805                exit 1
1806        fi
1807else
[cc7eab7]1808        echoAndLog "Web Console database exists, ommiting creation"
[a01156a]1809fi
1810
[09bf701]1811mysqlCheckUserExists ${OPENGNSYS_DB_USER}
[a01156a]1812if [ $? -ne 0 ]; then
1813        echoAndLog "Creating user in database"
[09bf701]1814        mysqlCreateAdminUserToDb ${OPENGNSYS_DATABASE} ${OPENGNSYS_DB_USER} "${OPENGNSYS_DB_PASSWD}"
[a01156a]1815        if [ $? -ne 0 ]; then
[cc7eab7]1816                errorAndLog "Error while creating database user"
[a01156a]1817                exit 1
1818        fi
1819
1820fi
1821
[09bf701]1822mysqlCheckDbIsEmpty ${OPENGNSYS_DATABASE}
[a01156a]1823if [ $? -eq 0 ]; then
1824        echoAndLog "Creating tables..."
[892606b9]1825        if [ -f $WORKDIR/$OPENGNSYS_DB_CREATION_FILE ]; then
[09bf701]1826                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_CREATION_FILE
[a01156a]1827        else
[892606b9]1828                errorAndLog "Unable to locate $WORKDIR/$OPENGNSYS_DB_CREATION_FILE!!"
[a01156a]1829                exit 1
1830        fi
[bc7dfe7]1831else
1832        # Si existe fichero ogBDAdmin-VersLocal-VersRepo.sql; aplicar cambios.
[9815cac]1833        REPOVERSION=$(jq -r '.version' $WORKDIR/opengnsys/doc/VERSION.json)
[295b4ab]1834        OPENGNSYS_DB_UPDATE_FILE="opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
1835        if [ -f $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE ]; then
[bc7dfe7]1836                echoAndLog "Updating tables from version $INSTVERSION to $REPOVERSION"
[09bf701]1837                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE
[bc7dfe7]1838        else
1839                echoAndLog "Database unchanged."
1840        fi
[a01156a]1841fi
[09bf701]1842# Eliminar fichero temporal con credenciales de acceso a MySQL.
1843rm -f $TMPMYCNF
[a01156a]1844
[5f21d34]1845# Copiando páqinas web.
[7586ca3]1846installWebFiles
[ec045b1]1847# Descargar/descomprimir archivos descargables.
1848installDownloadableFiles
[5d6bf97]1849# Generar páqinas web de documentación de la API
1850makeDoxygenFiles
[a01156a]1851
[5f21d34]1852# Creando configuración de Apache.
[5fcf180]1853installWebConsoleApacheConf $INSTALL_TARGET $APACHECFGDIR
[a01156a]1854if [ $? -ne 0 ]; then
[5f21d34]1855        errorAndLog "Error configuring Apache for OpenGnsys Admin"
[a01156a]1856        exit 1
1857fi
1858
1859popd
[892606b9]1860
[9ef8920]1861# Crear la estructura de los accesos al servidor desde el cliente (shared)
[73a1bd6]1862copyClientFiles
[9ef8920]1863if [ $? -ne 0 ]; then
1864        errorAndLog "Error creating client structure"
1865fi
1866
[5050850]1867# Crear certificado para firmar cargadores
1868createCerts
1869
[5f21d34]1870# Crear la estructura del cliente de OpenGnsys.
[6019b12]1871for i in $OGLIVE; do
1872        if ! clientCreate "$i"; then
1873                errorAndLog "Error creating client $i"
1874                exit 1
1875        fi
1876done
[892606b9]1877
[5f21d34]1878# Configuración de servicios de OpenGnsys
[65245d1]1879openGnsysConfigure
1880
[180a07dd]1881# Mostrar sumario de la instalación e instrucciones de post-instalación.
1882installationSummary
1883
[3964e74]1884rm -rf $WORKDIR
[5f21d34]1885echoAndLog "OpenGnsys installation finished at $(date)"
[05d2e03]1886exit 0
[2308fc7]1887
Note: See TracBrowser for help on using the repository browser.