source: installer/opengnsys_installer.sh @ 560358b

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

#915: Add new ogAdmServer compilation dependency.

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