source: installer/opengnsys_installer.sh @ 01a36ca

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 01a36ca was 87c7b02, checked in by ramon <ramongomez@…>, 13 years ago

Versión 1.0.3, #414: Preparar instalador para distribución Debian.

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

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