source: installer/opengnsys_installer.sh @ 80cbc63

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacionwebconsole3
Last change on this file since 80cbc63 was 37481d8, checked in by Ramón M. Gómez <ramongomez@…>, 6 years ago

#784: Apache configuration now supports connection with PHP-FPM via socket and port.

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