source: installer/opengnsys_installer.sh @ eb4614b

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

#647: Instalar/actualizar usando arp-scan de CentOS 6 para servidores CentOS 7 (no existe en esta versión).

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

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