source: installer/opengnsys_installer.sh @ d8f592d

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

#730: Revisión correcta de ogLive 1.1.0-rc3.

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

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