source: installer/opengnsys_installer.sh @ 1452cbd

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 1452cbd was e9722d2, checked in by adv <adv@…>, 14 years ago

version1.0 #368 instalador y actualizador usando cliente 1.0.1

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

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