source: installer/opengnsys_installer.sh @ 08720c1

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 08720c1 was 05d2e03, checked in by ramon <ramongomez@…>, 13 years ago

Versión 1.0.3, #454: Algunas mejoras en el buscador básico de equipos.

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

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