source: installer/opengnsys_installer.sh @ aeb4951

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 aeb4951 was a43e90d, checked in by ramon <ramongomez@…>, 10 years ago

#659: Instalador y actualizador comprueban si tienen que renombrar Rsync para evitar la incompativilidad de versiones entre servidor y cliente.

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

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