source: installer/opengnsys_installer.sh @ a9c232f

918-git-images-111dconfigure-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 a9c232f was b77345f, checked in by Ramón M. Gómez <ramongomez@…>, 5 years ago

#959: Installer and updater download the lastest OGAgent version.

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