source: installer/opengnsys_installer.sh @ 7d09bd7

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

Usar nuevas URLs de descarga en instalador y actualizador (modificar #831).

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

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