source: installer/opengnsys_installer.sh @ 51c2318

Last change on this file since 51c2318 was 8ff5800, checked in by ramon <ramongomez@…>, 13 years ago

Versión 1.0.4a, #556: Corregidas erratas en instalador:

  • detectar las IPs de todas las redes en servidores con varias tarjetas,
  • parchear correctamente la configuración de Samba,
  • mostrar la URL de acceso a la consola web usando HTTPS.

git-svn-id: https://opengnsys.es/svn/trunk@3378 a21b9725-9963-47de-94b9-378ad31fedc9

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