source: installer/opengnsys_installer.sh @ 1f86917

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 1f86917 was a16ce1b, checked in by ramon <ramongomez@…>, 8 years ago

#730: Dejar de soportar Syslinux.

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

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