source: installer/opengnsys_installer.sh @ 12e1eef

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

#915: Installing a new ogAdmServer compilation dependency, if needed.

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