source: installer/opengnsys_installer.sh @ ac2d1cc

Last change on this file since ac2d1cc was c3648b9, checked in by Irina Gómez <irinagomez@…>, 4 years ago

#1026 The installation script displays information message only when distribution is different than advised.

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