source: installer/opengnsys_installer.sh @ 1f75d13

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 1f75d13 was b80226e, checked in by Irina Gómez <irinagomez@…>, 7 years ago

#867 Acceso al manual de usuario desde la consola web.

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