source: installer/opengnsys_installer.sh @ fb148e6

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-instalacion
Last change on this file since fb148e6 was fb148e6, checked in by Ramón M. Gómez <ramongomez@…>, 6 years ago

#872: Download correct OGAgent version.

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