source: installer/opengnsys_installer.sh @ a6d6d6f

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 a6d6d6f was 8b8e948, checked in by ramon <ramongomez@…>, 9 years ago

#708: Instalar librería Swagger-UI en el servidor para documentar la API REST a partir del fichero YAML.

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

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