source: installer/opengnsys_installer.sh @ a30ad15f

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

#718 #730: Incluir rutas REST que atienden las peticiones push del nuevo OGAgent y actualización de la ubicación del fichero para registrarlas.

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

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