source: installer/opengnsys_installer.sh @ fc9a1ad

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacionwebconsole3
Last change on this file since fc9a1ad was 1635f45, checked in by ramon <ramongomez@…>, 7 years ago

#804: Dejar de instalar antigua librería xajax incompatible con PHP 7.

git-svn-id: https://opengnsys.es/svn/branches/version1.1@5626 a21b9725-9963-47de-94b9-378ad31fedc9

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