source: installer/opengnsys_installer_devel_esxi.sh @ 915580e

configure-oglivelgromero-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 915580e was 3513239, checked in by Natalia Serrano <natalia.serrano@…>, 20 months ago

Trivial additions

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