source: installer/opengnsys_installer.sh @ 20476f5

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacionwebconsole3
Last change on this file since 20476f5 was 1be256f, checked in by Irina Gómez <irinagomez@…>, 7 years ago

#846 Se configura logrotate para que incluya todos los archivos de registro. Se separan los servicios del server y del repo en archivos independientes

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