source: installer/opengnsys_installer.sh @ e57b608

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 e57b608 was 6bd2e1e, checked in by Ramón M. Gómez <ramongomez@…>, 6 years ago

#736: Installer script no longer disables firewall or SELinux, and recommends using security-config script.

  • 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        INSTVERSION=1.1.0       ###  Temporal.
1085        local FILENAME=ogagentpkgs-$INSTVERSION.tar.gz
1086        local TARGETFILE=$WORKDIR/$FILENAME
1087 
1088        # Descargar archivo comprimido, si es necesario.
1089        if [ -s $PROGRAMDIR/$FILENAME ]; then
1090                echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
1091                mv $PROGRAMDIR/$FILENAME $TARGETFILE
1092        else
1093                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
1094                curl $DOWNLOADURL/$FILENAME -o $TARGETFILE
1095        fi
1096        if [ ! -s $TARGETFILE ]; then
1097                errorAndLog "${FUNCNAME}(): Cannot download $FILENAME"
1098                return 1
1099        fi
1100       
1101        # Descomprimir fichero en zona de descargas.
1102        tar xvzf $TARGETFILE -C $INSTALL_TARGET/www/descargas
1103        if [ $? != 0 ]; then
1104                errorAndLog "${FUNCNAME}(): Error uncompressing archive."
1105                exit 1
1106        fi
1107}
1108
1109# Configuración específica de Apache.
1110function installWebConsoleApacheConf()
1111{
1112        if [ $# -ne 2 ]; then
1113                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1114                exit 1
1115        fi
1116
1117        local path_opengnsys_base="$1"
1118        local path_apache2_confd="$2"
1119        local CONSOLEDIR=${path_opengnsys_base}/www
1120        local sockfile
1121
1122        if [ ! -d $path_apache2_confd ]; then
1123                errorAndLog "${FUNCNAME}(): path to apache2 conf.d can not found, verify your server installation"
1124                return 1
1125        fi
1126
1127        mkdir -p $path_apache2_confd/{sites-available,sites-enabled}
1128
1129        echoAndLog "${FUNCNAME}(): creating apache2 config file.."
1130
1131        # Avtivar PHP-FPM.
1132        echoAndLog "${FUNCNAME}(): configuring PHP-FPM"
1133        service=$PHPFPMSERV
1134        $ENABLESERVICE; $STARTSERVICE
1135        sockfile=$(find /run/php -name "php*.sock" -type s -print 2>/dev/null | tail -1)
1136
1137        # Activar módulos de Apache.
1138        $APACHEENABLEMODS
1139        # Activar HTTPS.
1140        $APACHEENABLESSL
1141        $APACHEMAKECERT
1142        # Genera configuración de consola web a partir del fichero plantilla.
1143        if [ -n "$(apachectl -v | grep "2\.[0-2]")" ]; then
1144                # Configuración para versiones anteriores de Apache.
1145                sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
1146                        $WORKDIR/opengnsys/server/etc/apache-prev2.4.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}
1147        else
1148                # Configuración específica a partir de Apache 2.4
1149                if [ -n "$sockfile" ]; then
1150                        sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
1151                            -e "s,proxy:fcgi:.*,proxy:unix:${sockfile%% *}|fcgi://localhost\",g" \
1152                                $WORKDIR/opengnsys/server/etc/apache.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf
1153                else
1154                        sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
1155                                $WORKDIR/opengnsys/server/etc/apache.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf
1156                fi
1157        fi
1158        $APACHEENABLEOG
1159        if [ $? -ne 0 ]; then
1160                errorAndLog "${FUNCNAME}(): config file can't be linked to apache conf, verify your server installation"
1161                return 1
1162        fi
1163        echoAndLog "${FUNCNAME}(): config file created and linked, restarting apache daemon"
1164        service=$APACHESERV
1165        $ENABLESERVICE; $STARTSERVICE
1166        return 0
1167}
1168
1169
1170# Crear documentación Doxygen para la consola web.
1171function makeDoxygenFiles()
1172{
1173        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
1174        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
1175                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
1176        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
1177                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
1178                return 1
1179        fi
1180        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
1181        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
1182}
1183
1184
1185# Crea la estructura base de la instalación de opengnsys
1186function createDirs()
1187{
1188        if [ $# -ne 1 ]; then
1189                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1190                exit 1
1191        fi
1192
1193        local path_opengnsys_base="$1"
1194
1195        # Crear estructura de directorios.
1196        echoAndLog "${FUNCNAME}(): creating directory paths in $path_opengnsys_base"
1197        mkdir -p $path_opengnsys_base
1198        mkdir -p $path_opengnsys_base/bin
1199        mkdir -p $path_opengnsys_base/client/{cache,images,log}
1200        mkdir -p $path_opengnsys_base/doc
1201        mkdir -p $path_opengnsys_base/etc
1202        mkdir -p $path_opengnsys_base/lib
1203        mkdir -p $path_opengnsys_base/log/clients
1204        ln -fs $path_opengnsys_base/log /var/log/opengnsys
1205        mkdir -p $path_opengnsys_base/sbin
1206        mkdir -p $path_opengnsys_base/www
1207        mkdir -p $path_opengnsys_base/images/groups
1208        mkdir -p $TFTPCFGDIR
1209        ln -fs $TFTPCFGDIR $path_opengnsys_base/tftpboot
1210        mkdir -p $path_opengnsys_base/tftpboot/{menu.lst,grub}
1211        if [ $? -ne 0 ]; then
1212                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
1213                return 1
1214        fi
1215
1216        # Crear usuario ficticio.
1217        if id -u $OPENGNSYS_CLIENT_USER &>/dev/null; then
1218                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENT_USER\" is already created"
1219        else
1220                echoAndLog "${FUNCNAME}(): creating OpenGnsys user"
1221                useradd $OPENGNSYS_CLIENT_USER 2>/dev/null
1222                if [ $? -ne 0 ]; then
1223                        errorAndLog "${FUNCNAME}(): error creating OpenGnsys user"
1224                        return 1
1225                fi
1226        fi
1227
1228        # Mover el fichero de registro de instalación al directorio de logs.
1229        echoAndLog "${FUNCNAME}(): moving installation log file"
1230        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
1231        chmod 600 $LOG_FILE
1232
1233        echoAndLog "${FUNCNAME}(): directory paths created"
1234        return 0
1235}
1236
1237# Copia ficheros de configuración y ejecutables genéricos del servidor.
1238function copyServerFiles ()
1239{
1240        if [ $# -ne 1 ]; then
1241                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1242                exit 1
1243        fi
1244
1245        local path_opengnsys_base="$1"
1246
1247        # Lista de ficheros y directorios origen y de directorios destino.
1248        local SOURCES=( server/tftpboot \
1249                        /usr/lib/shim/shimx64.efi.signed \
1250                        /usr/lib/grub/x86_64-efi-signed/grubnetx64.efi.signed \
1251                        server/bin \
1252                        repoman/bin \
1253                        server/lib \
1254                        admin/Sources/Services/ogAdmServerAux
1255                        admin/Sources/Services/ogAdmRepoAux
1256                        installer/opengnsys_uninstall.sh \
1257                        installer/opengnsys_update.sh \
1258                        installer/opengnsys_export.sh \
1259                        installer/opengnsys_import.sh \
1260                        doc )
1261        local TARGETS=( tftpboot \
1262                        tftpboot \
1263                        tftpboot/grubx64.efi \
1264                        bin \
1265                        bin \
1266                        lib \
1267                        sbin \
1268                        sbin \
1269                        lib \
1270                        lib \
1271                        lib \
1272                        lib \
1273                        doc )
1274
1275        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
1276                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
1277                exit 1
1278        fi
1279
1280        # Copiar ficheros.
1281        echoAndLog "${FUNCNAME}(): copying files to server directories"
1282
1283        pushd $WORKDIR/opengnsys
1284        local i
1285        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
1286                if [ -f "${SOURCES[$i]}" ]; then
1287                        echoAndLog "Copying ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1288                        cp -a "${SOURCES[$i]}" "${path_opengnsys_base}/${TARGETS[$i]}"
1289                elif [ -d "${SOURCES[$i]}" ]; then
1290                        echoAndLog "Copying content of ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1291                        cp -a "${SOURCES[$i]}"/* "${path_opengnsys_base}/${TARGETS[$i]}"
1292                else
1293                        warningAndLog "Unable to copy ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1294                fi
1295        done
1296
1297        popd
1298}
1299
1300####################################################################
1301### Funciones de compilación de código fuente de servicios
1302####################################################################
1303
1304# Compilar los servicios de OpenGnsys
1305function servicesCompilation ()
1306{
1307        local hayErrores=0
1308
1309        # Compilar OpenGnsys Server
1310        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Server"
1311        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
1312        make && mv ogAdmServer $INSTALL_TARGET/sbin
1313        if [ $? -ne 0 ]; then
1314                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Server"
1315                hayErrores=1
1316        fi
1317        popd
1318        # Compilar OpenGnsys Agent
1319        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Agent"
1320        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
1321        make && mv ogAdmAgent $INSTALL_TARGET/sbin
1322        if [ $? -ne 0 ]; then
1323                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Agent"
1324                hayErrores=1
1325        fi
1326        popd   
1327        # Compilar OpenGnsys Client
1328        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Client"
1329        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
1330        make && mv ogAdmClient ../../../../client/shared/bin
1331        if [ $? -ne 0 ]; then
1332                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Client"
1333                hayErrores=1
1334        fi
1335        popd
1336
1337        return $hayErrores
1338}
1339
1340####################################################################
1341### Funciones de copia de la Interface de administración
1342####################################################################
1343
1344# Copiar carpeta de Interface
1345function copyInterfaceAdm ()
1346{
1347        local hayErrores=0
1348       
1349        # Crear carpeta y copiar Interface
1350        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
1351        cp -ar $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client/interfaceAdm
1352        if [ $? -ne 0 ]; then
1353                echoAndLog "${FUNCNAME}(): error while copying Administration Interface Folder"
1354                hayErrores=1
1355        fi
1356        chown $OPENGNSYS_CLIENT_USER:$OPENGNSYS_CLIENT_USER $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
1357        chmod 700 $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
1358
1359        return $hayErrores
1360}
1361
1362####################################################################
1363### Funciones instalacion cliente opengnsys
1364####################################################################
1365
1366function copyClientFiles()
1367{
1368        local errstatus=0
1369
1370        echoAndLog "${FUNCNAME}(): Copying OpenGnsys Client files."
1371        cp -a $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
1372        if [ $? -ne 0 ]; then
1373                errorAndLog "${FUNCNAME}(): error while copying client estructure"
1374                errstatus=1
1375        fi
1376       
1377        echoAndLog "${FUNCNAME}(): Copying OpenGnsys Cloning Engine files."
1378        mkdir -p $INSTALL_TARGET/client/lib/engine/bin
1379        cp -a $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
1380        if [ $? -ne 0 ]; then
1381                errorAndLog "${FUNCNAME}(): error while copying engine files"
1382                errstatus=1
1383        fi
1384       
1385        if [ $errstatus -eq 0 ]; then
1386                echoAndLog "${FUNCNAME}(): client copy files success."
1387        else
1388                errorAndLog "${FUNCNAME}(): client copy files with errors"
1389        fi
1390
1391        return $errstatus
1392}
1393
1394
1395# Crear cliente OpenGnsys.
1396function clientCreate()
1397{
1398        if [ $# -ne 1 ]; then
1399                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1400                exit 1
1401        fi
1402
1403        local FILENAME="$1"
1404        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
1405 
1406        # Descargar cliente, si es necesario.
1407        if [ -s $PROGRAMDIR/$FILENAME ]; then
1408                echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
1409                mv $PROGRAMDIR/$FILENAME $TARGETFILE
1410        else
1411                echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
1412                oglivecli download $FILENAME
1413        fi
1414        if [ ! -s $TARGETFILE ]; then
1415                errorAndLog "${FUNCNAME}(): Error loading $FILENAME"
1416                return 1
1417        fi
1418
1419        # Montar imagen, copiar cliente ogclient y desmontar.
1420        echoAndLog "${FUNCNAME}(): Installing ogLive Client"
1421        echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | \
1422                        oglivecli install $FILENAME
1423        # Adaptar permisos.
1424        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/tftpboot/menu.lst
1425
1426        echoAndLog "${FUNCNAME}(): Client generation success"
1427}
1428
1429
1430# Configuración básica de servicios de OpenGnsys
1431function openGnsysConfigure()
1432{
1433        local i=0
1434        local dev=""
1435        local CONSOLEURL
1436
1437        echoAndLog "${FUNCNAME}(): Copying init files."
1438        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
1439        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default /etc/default/opengnsys
1440        # Deshabilitar servicios de BitTorrent si no están instalados.
1441        if [ ! -e /usr/bin/bttrack ]; then
1442                sed -i 's/RUN_BTTRACKER="yes"/RUN_BTTRACKER="no"/; s/RUN_BTSEEDER="yes"/RUN_BTSEEDER="no"/' \
1443                        /etc/default/opengnsys
1444        fi
1445        echoAndLog "${FUNCNAME}(): Creating cron files."
1446        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
1447        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
1448        echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
1449        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
1450        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/ogagentqueue.cron ] && $INSTALL_TARGET/bin/ogagentqueue.cron" > /etc/cron.d/ogagentqueue
1451
1452        echoAndLog "${FUNCNAME}(): Creating logrotate configuration files."
1453        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1454                $WORKDIR/opengnsys/server/etc/logrotate.tmpl > /etc/logrotate.d/opengnsysServer
1455
1456        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1457                $WORKDIR/opengnsys/repoman/etc/logrotate.tmpl > /etc/logrotate.d/opengnsysRepo
1458
1459        echoAndLog "${FUNCNAME}(): Creating OpenGnsys config files."
1460        for dev in ${DEVICE[*]}; do
1461                if [ -n "${SERVERIP[i]}" ]; then
1462                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1463                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1464                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1465                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1466                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer/ogAdmServer.cfg > $INSTALL_TARGET/etc/ogAdmServer-$dev.cfg
1467                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1468                            -e "s/REPOKEY/$OPENGNSYS_REPOKEY/g" \
1469                                $WORKDIR/opengnsys/repoman/etc/ogAdmRepo.cfg.tmpl > $INSTALL_TARGET/etc/ogAdmRepo-$dev.cfg
1470                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1471                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1472                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1473                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1474                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent/ogAdmAgent.cfg > $INSTALL_TARGET/etc/ogAdmAgent-$dev.cfg
1475                        CONSOLEURL="https://${SERVERIP[i]}/opengnsys"
1476                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1477                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1478                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1479                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1480                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
1481                                $INSTALL_TARGET/www/controlacceso.php > $INSTALL_TARGET/www/controlacceso-$dev.php
1482                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1483                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
1484                                $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient/ogAdmClient.cfg > $INSTALL_TARGET/client/etc/ogAdmClient-$dev.cfg
1485                        if [ "$dev" == "$DEFAULTDEV" ]; then
1486                                OPENGNSYS_CONSOLEURL="$CONSOLEURL"
1487                        fi
1488                fi
1489                let i++
1490        done
1491        ln -f $INSTALL_TARGET/etc/ogAdmServer-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmServer.cfg
1492        ln -f $INSTALL_TARGET/etc/ogAdmRepo-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmRepo.cfg
1493        ln -f $INSTALL_TARGET/etc/ogAdmAgent-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmAgent.cfg
1494        ln -f $INSTALL_TARGET/client/etc/ogAdmClient-$DEFAULTDEV.cfg $INSTALL_TARGET/client/etc/ogAdmClient.cfg
1495        ln -f $INSTALL_TARGET/www/controlacceso-$DEFAULTDEV.php $INSTALL_TARGET/www/controlacceso.php
1496        chown root:root $INSTALL_TARGET/etc/{ogAdmServer,ogAdmAgent}*.cfg
1497        chmod 600 $INSTALL_TARGET/etc/{ogAdmServer,ogAdmAgent}*.cfg
1498        chown $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/controlacceso*.php
1499        chmod 600 $INSTALL_TARGET/www/controlacceso*.php
1500
1501        # Configuración del motor de clonación.
1502        # - Zona horaria del servidor.
1503        TZ=$(timedatectl status|awk -F"[:()]" '/Time.*zone/ {print $2}')
1504        cat << EOT >> $INSTALL_TARGET/client/etc/engine.cfg
1505# OpenGnsys Server timezone.
1506TZ="${TZ// /}"
1507EOT
1508
1509        # Revisar permisos generales.
1510        if [ -x $INSTALL_TARGET/bin/checkperms ]; then
1511                echoAndLog "${FUNCNAME}(): Checking permissions."
1512                OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENT_USER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" checkperms
1513        fi
1514
1515        # Evitar inicio de duplicado en Ubuntu 14.04 (Upstart y SysV Init).
1516        if [ -f /etc/init/${MYSQLSERV}.conf -a -n "$(which initctl 2>/dev/null)" ]; then
1517                service=$MYSQLSERV
1518                $DISABLESERVICE
1519        fi
1520
1521        echoAndLog "${FUNCNAME}(): Starting OpenGnsys services."
1522        service="opengnsys"
1523        $ENABLESERVICE; $STARTSERVICE
1524}
1525
1526
1527#####################################################################
1528#######  Función de resumen informativo de la instalación
1529#####################################################################
1530
1531function installationSummary()
1532{
1533        local VERSIONFILE REVISION
1534
1535        # Crear fichero de versión y revisión, si no existe.
1536        VERSIONFILE="$INSTALL_TARGET/doc/VERSION.json"
1537        [ -f $VERSIONFILE ] || echo '{ "project": "OpenGnsys" }' >$VERSIONFILE
1538        # Incluir datos de revisión, si se está instalando desde el repositorio
1539        # de código o si no está incluida en el fichero de versión.
1540        if [ $REMOTE -eq 1 ] || [ -z "$(jq -r '.release' $VERSIONFILE)" ]; then
1541                # Revisión: rAñoMesDía.Gitcommit (8 caracteres de fecha y 7 primeros de commit).
1542                REVISION=$(curl -s "$API_URL" | jq '"r" + (.commit.commit.committer.date | split("-") | join("")[:8]) + "." + (.commit.sha[:7])')
1543                jq ".release=$REVISION" $VERSIONFILE | sponge $VERSIONFILE
1544        fi
1545        VERSION="$(jq -r '[.project, .version, .codename, .release] | join(" ")' $VERSIONFILE 2>/dev/null)"
1546
1547        # Mostrar información.
1548        echo
1549        echoAndLog "OpenGnsys Installation Summary"
1550        echo       "=============================="
1551        echoAndLog "Project version:                  $VERSION"
1552        echoAndLog "Installation directory:           $INSTALL_TARGET"
1553        echoAndLog "Installation log file:            $LOG_FILE"
1554        echoAndLog "Repository directory:             $INSTALL_TARGET/images"
1555        echoAndLog "DHCP configuration directory:     $DHCPCFGDIR"
1556        echoAndLog "TFTP configuration directory:     $TFTPCFGDIR"
1557        echoAndLog "Installed ogLive client(s):       $(oglivecli list | awk '{print $2}')"
1558        echoAndLog "Samba configuration directory:    $SAMBACFGDIR"
1559        echoAndLog "Web Console URL:                  $OPENGNSYS_CONSOLEURL"
1560        echoAndLog "Web Console access data:          entered by the user"
1561        if grep -q "^RUN_BTTRACK.*no" /etc/default/opengnsys; then
1562                echoAndLog "BitTorrent service is disabled."
1563        fi
1564        echo
1565        echoAndLog "Post-Installation Instructions:"
1566        echo       "==============================="
1567        echoAndLog "You can improve server security by configuring firewall and SELinux,"
1568        echoAndLog "   running \"$INSTALL_TARGET/lib/security-config\" script as root."
1569        echoAndLog "It's strongly recommended to synchronize this server with an NTP server."
1570        echoAndLog "Review or edit all configuration files."
1571        echoAndLog "Insert DHCP configuration data and restart service."
1572        echoAndLog "Optional: Log-in as Web Console admin user."
1573        echoAndLog " - Review default Organization data and assign access to users."
1574        echoAndLog "Log-in as Web Console organization user."
1575        echoAndLog " - Insert OpenGnsys data (labs, computers, menus, etc)."
1576echo
1577}
1578
1579
1580
1581#####################################################################
1582####### Proceso de instalación de OpenGnsys
1583#####################################################################
1584
1585echoAndLog "OpenGnsys installation begins at $(date)"
1586pushd $WORKDIR
1587
1588# Detectar datos iniciales de auto-configuración del instalador.
1589autoConfigure
1590
1591# Detectar parámetros de red y comprobar si hay conexión.
1592getNetworkSettings
1593if [ $? -ne 0 ]; then
1594        errorAndLog "Error reading default network settings."
1595        exit 1
1596fi
1597checkNetworkConnection
1598if [ $? -ne 0 ]; then
1599        errorAndLog "Error connecting to server. Causes:"
1600        errorAndLog " - Network is unreachable, review devices parameters."
1601        errorAndLog " - You are inside a private network, configure the proxy service."
1602        errorAndLog " - Server is temporally down, try agian later."
1603        exit 1
1604fi
1605
1606# Detener servicios de OpenGnsys, si están activos previamente.
1607[ -f /etc/init.d/opengnsys ] && /etc/init.d/opengnsys stop
1608
1609# Actualizar repositorios
1610updatePackageList
1611
1612# Instalación de dependencias (paquetes de sistema operativo).
1613declare -a notinstalled
1614checkDependencies DEPENDENCIES notinstalled
1615if [ $? -ne 0 ]; then
1616        installDependencies notinstalled
1617        if [ $? -ne 0 ]; then
1618                echoAndLog "Error while installing some dependeces, please verify your server installation before continue"
1619                exit 1
1620        fi
1621fi
1622if [ -n "$INSTALLEXTRADEPS" ]; then
1623        echoAndLog "Installing extra dependencies"
1624        for (( i=0; i<${#INSTALLEXTRADEPS[*]}; i++ )); do
1625                eval ${INSTALLEXTRADEPS[i]}
1626        done
1627fi     
1628
1629# Detectar datos de auto-configuración después de instalar paquetes.
1630autoConfigurePost
1631
1632# Arbol de directorios de OpenGnsys.
1633createDirs ${INSTALL_TARGET}
1634if [ $? -ne 0 ]; then
1635        errorAndLog "Error while creating directory paths!"
1636        exit 1
1637fi
1638
1639# Si es necesario, descarga el repositorio de código en directorio temporal
1640if [ $REMOTE -eq 1 ]; then
1641        downloadCode $CODE_URL
1642        if [ $? -ne 0 ]; then
1643                errorAndLog "Error while getting code from the repository"
1644                exit 1
1645        fi
1646else
1647        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
1648fi
1649
1650# Compilar código fuente de los servicios de OpenGnsys.
1651servicesCompilation
1652if [ $? -ne 0 ]; then
1653        errorAndLog "Error while compiling OpenGnsys services"
1654        exit 1
1655fi
1656
1657# Copiar carpeta Interface entre administración y motor de clonación.
1658copyInterfaceAdm
1659if [ $? -ne 0 ]; then
1660        errorAndLog "Error while copying Administration Interface"
1661        exit 1
1662fi
1663
1664# Configuración de TFTP.
1665tftpConfigure
1666
1667# Configuración de Samba.
1668smbConfigure
1669if [ $? -ne 0 ]; then
1670        errorAndLog "Error while configuring Samba server!"
1671        exit 1
1672fi
1673
1674# Configuración de Rsync.
1675rsyncConfigure
1676
1677# Configuración ejemplo DHCP.
1678dhcpConfigure
1679if [ $? -ne 0 ]; then
1680        errorAndLog "Error while copying your dhcp server files!"
1681        exit 1
1682fi
1683
1684# Copiar ficheros de servicios OpenGnsys Server.
1685copyServerFiles ${INSTALL_TARGET}
1686if [ $? -ne 0 ]; then
1687        errorAndLog "Error while copying the server files!"
1688        exit 1
1689fi
1690INSTVERSION=$(jq -r '.version' $INSTALL_TARGET/doc/VERSION.json)
1691
1692# Instalar base de datos de OpenGnsys Admin.
1693isInArray notinstalled "mysql-server" || isInArray notinstalled "mariadb-server"
1694if [ $? -eq 0 ]; then
1695        # Habilitar gestor de base de datos (MySQL, si falla, MariaDB).
1696        service=$MYSQLSERV
1697        $ENABLESERVICE
1698        if [ $? != 0 ]; then
1699                service=$MARIADBSERV
1700                $ENABLESERVICE
1701        fi
1702        # Activar gestor de base de datos.
1703        $STARTSERVICE
1704        # Asignar clave del usuario "root".
1705        mysqlSetRootPassword "${MYSQL_ROOT_PASSWORD}"
1706else
1707        # Si ya está instalado el gestor de bases de datos, obtener clave de "root",
1708        mysqlGetRootPassword
1709fi
1710
1711mysqlTestConnection "${MYSQL_ROOT_PASSWORD}"
1712if [ $? -ne 0 ]; then
1713        errorAndLog "Error while connection to mysql"
1714        exit 1
1715fi
1716mysqlDbExists ${OPENGNSYS_DATABASE}
1717if [ $? -ne 0 ]; then
1718        echoAndLog "Creating Web Console database"
1719        mysqlCreateDb ${OPENGNSYS_DATABASE}
1720        if [ $? -ne 0 ]; then
1721                errorAndLog "Error while creating Web Console database"
1722                exit 1
1723        fi
1724else
1725        echoAndLog "Web Console database exists, ommiting creation"
1726fi
1727
1728mysqlCheckUserExists ${OPENGNSYS_DB_USER}
1729if [ $? -ne 0 ]; then
1730        echoAndLog "Creating user in database"
1731        mysqlCreateAdminUserToDb ${OPENGNSYS_DATABASE} ${OPENGNSYS_DB_USER} "${OPENGNSYS_DB_PASSWD}"
1732        if [ $? -ne 0 ]; then
1733                errorAndLog "Error while creating database user"
1734                exit 1
1735        fi
1736
1737fi
1738
1739mysqlCheckDbIsEmpty ${OPENGNSYS_DATABASE}
1740if [ $? -eq 0 ]; then
1741        echoAndLog "Creating tables..."
1742        if [ -f $WORKDIR/$OPENGNSYS_DB_CREATION_FILE ]; then
1743                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_CREATION_FILE
1744        else
1745                errorAndLog "Unable to locate $WORKDIR/$OPENGNSYS_DB_CREATION_FILE!!"
1746                exit 1
1747        fi
1748else
1749        # Si existe fichero ogBDAdmin-VersLocal-VersRepo.sql; aplicar cambios.
1750        REPOVERSION=$(jq -r '.version' $WORKDIR/opengnsys/doc/VERSION.json)
1751        OPENGNSYS_DB_UPDATE_FILE="opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
1752        if [ -f $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE ]; then
1753                echoAndLog "Updating tables from version $INSTVERSION to $REPOVERSION"
1754                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE
1755        else
1756                echoAndLog "Database unchanged."
1757        fi
1758fi
1759# Eliminar fichero temporal con credenciales de acceso a MySQL.
1760rm -f $TMPMYCNF
1761
1762# Copiando páqinas web.
1763installWebFiles
1764# Descargar/descomprimir archivos descargables.
1765installDownloadableFiles
1766# Generar páqinas web de documentación de la API
1767makeDoxygenFiles
1768
1769# Creando configuración de Apache.
1770installWebConsoleApacheConf $INSTALL_TARGET $APACHECFGDIR
1771if [ $? -ne 0 ]; then
1772        errorAndLog "Error configuring Apache for OpenGnsys Admin"
1773        exit 1
1774fi
1775
1776popd
1777
1778# Crear la estructura de los accesos al servidor desde el cliente (shared)
1779copyClientFiles
1780if [ $? -ne 0 ]; then
1781        errorAndLog "Error creating client structure"
1782fi
1783
1784# Crear la estructura del cliente de OpenGnsys.
1785for i in $OGLIVE; do
1786        if ! clientCreate "$i"; then
1787                errorAndLog "Error creating client $i"
1788                exit 1
1789        fi
1790done
1791
1792# Configuración de servicios de OpenGnsys
1793openGnsysConfigure
1794
1795# Mostrar sumario de la instalación e instrucciones de post-instalación.
1796installationSummary
1797
1798#rm -rf $WORKDIR
1799echoAndLog "OpenGnsys installation finished at $(date)"
1800exit 0
1801
Note: See TracBrowser for help on using the repository browser.