source: installer/opengnsys_installer.sh @ 3fef8e1

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 3fef8e1 was ea7186c, checked in by ramon <ramongomez@…>, 16 years ago

Script de listado de software para consola web.

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

  • Property mode set to 100755
File size: 32.8 KB
Line 
1#!/bin/bash
2
3#####################################################################
4####### Script instalador OpenGnsys
5####### autor: Luis Guillén <lguillen@unizar.es>
6#####################################################################
7
8
9WORKDIR=/tmp/opengnsys_installer
10LOG_FILE=/tmp/opengnsys_installation.log
11
12# Array con las dependencias
13DEPENDENCIES=( subversion apache2 php5 mysql-server php5-mysql nfs-kernel-server dhcp3-server udpcast bittorrent tftp-hpa tftpd-hpa syslinux openbsd-inetd update-inetd build-essential libmysqlclient15-dev wget doxygen graphviz)
14
15INSTALL_TARGET=/opt/opengnsys
16
17MYSQL_ROOT_PASSWORD="passwordroot"
18
19# conexión al svn
20SVN_URL=svn://www.informatica.us.es:3690/opengnsys/trunk
21
22# Datos de base de datos
23OPENGNSYS_DATABASE=ogBDAdmin
24OPENGNSYS_DB_USER=usuog
25OPENGNSYS_DB_PASSWD=passusuog
26OPENGNSYS_DB_DEFAULTUSER=opengnsys
27OPENGNSYS_DB_DEFAULTPASSWD=opengnsys
28OPENGNSYS_DB_CREATION_FILE=opengnsys/admin/Database/ogBDAdmin.sql
29
30USUARIO=`whoami`
31
32if [ $USUARIO != 'root' ]
33then
34        echo "ERROR: this program must run under root privileges!!"
35        exit 1
36fi
37
38
39mkdir -p $WORKDIR
40pushd $WORKDIR
41
42#####################################################################
43####### Algunas funciones útiles de propósito general:
44#####################################################################
45function getDateTime()
46{
47        echo `date +%Y%m%d-%H%M%S`
48}
49
50# Escribe a fichero y muestra por pantalla
51function echoAndLog()
52{
53        echo $1
54        FECHAHORA=`getDateTime`
55        echo "$FECHAHORA;$SSH_CLIENT;$1" >> $LOG_FILE
56}
57
58function errorAndLog()
59{
60        echo "ERROR: $1"
61        FECHAHORA=`getDateTime`
62        echo "$FECHAHORA;$SSH_CLIENT;ERROR: $1" >> $LOG_FILE
63}
64
65# comprueba si el elemento pasado en $2 esta en el array $1
66function isInArray()
67{
68        if [ $# -ne 2 ]; then
69                errorAndLog "${FUNCNAME}(): invalid number of parameters"
70                exit 1
71        fi
72
73        echoAndLog "${FUNCNAME}(): checking if $2 is in $1"
74        local deps
75        eval "deps=( \"\${$1[@]}\" )"
76        elemento=$2
77
78        local is_in_array=1
79        # copia local del array del parametro 1
80        for (( i = 0 ; i < ${#deps[@]} ; i++ ))
81        do
82                if [ "${deps[$i]}" = "${elemento}" ]; then
83                        echoAndLog "isInArray(): $elemento found in array"
84                        is_in_array=0
85                fi
86        done
87
88        if [ $is_in_array -ne 0 ]; then
89                echoAndLog "${FUNCNAME}(): $elemento NOT found in array"
90        fi
91
92        return $is_in_array
93
94}
95
96#####################################################################
97####### Funciones de manejo de paquetes Debian
98#####################################################################
99
100function checkPackage()
101{
102        package=$1
103        if [ -z $package ]; then
104                errorAndLog "checkPackage(): parameter required"
105                exit 1
106        fi
107        echoAndLog "checkPackage(): checking if package $package exists"
108        dpkg -L $package &>/dev/null
109        if [ $? -eq 0 ]; then
110                echoAndLog "checkPackage(): package $package exists"
111                return 0
112        else
113                echoAndLog "checkPackage(): package $package doesn't exists"
114                return 1
115        fi
116}
117
118# recibe array con dependencias
119# por referencia deja un array con las dependencias no resueltas
120# devuelve 1 si hay alguna dependencia no resuelta
121function checkDependencies()
122{
123        if [ $# -ne 2 ]; then
124                errorAndLog "checkDependencies(): invalid number of parameters"
125                exit 1
126        fi
127
128        echoAndLog "checkDependencies(): checking dependences"
129        uncompletedeps=0
130
131        # copia local del array del parametro 1
132        local deps
133        eval "deps=( \"\${$1[@]}\" )"
134
135        declare -a local_notinstalled
136
137        for (( i = 0 ; i < ${#deps[@]} ; i++ ))
138        do
139                checkPackage ${deps[$i]}
140                if [ $? -ne 0 ]; then
141                        local_notinstalled[$uncompletedeps]=$package
142                        let uncompletedeps=uncompletedeps+1
143                fi
144        done
145
146        # relleno el array especificado en $2 por referencia
147        for (( i = 0 ; i < ${#local_notinstalled[@]} ; i++ ))
148        do
149                eval "${2}[$i]=${local_notinstalled[$i]}"
150        done
151
152        # retorna el numero de paquetes no resueltos
153        echoAndLog "checkDependencies(): dependencies uncompleted: $uncompletedeps"
154        return $uncompletedeps
155}
156
157# Recibe un array con las dependencias y lo instala
158function installDependencies()
159{
160        if [ $# -ne 1 ]; then
161                errorAndLog "installDependencies(): invalid number of parameters"
162                exit 1
163        fi
164        echoAndLog "installDependencies(): installing uncompleted dependencies"
165
166        # copia local del array del parametro 1
167        local deps
168        eval "deps=( \"\${$1[@]}\" )"
169
170        local string_deps=""
171        for (( i = 0 ; i < ${#deps[@]} ; i++ ))
172        do
173                string_deps="$string_deps ${deps[$i]}"
174        done
175
176        if [ -z "${string_deps}" ]; then
177                errorAndLog "installDependencies(): array of dependeces is empty"
178                exit 1
179        fi
180
181        OLD_DEBIAN_FRONTEND=$DEBIAN_FRONTEND
182        export DEBIAN_FRONTEND=noninteractive
183
184        echoAndLog "installDependencies(): now ${string_deps} will be installed"
185        apt-get -y install --force-yes ${string_deps}
186        if [ $? -ne 0 ]; then
187                errorAndLog "installDependencies(): error installing dependencies"
188                return 1
189        fi
190
191        DEBIAN_FRONTEND=$OLD_DEBIAN_FRONTEND
192        echoAndLog "installDependencies(): dependencies installed"
193}
194
195# Hace un backup del fichero pasado por parámetro
196# deja un -last y uno para el día
197function backupFile()
198{
199        if [ $# -ne 1 ]; then
200                errorAndLog "${FUNCNAME}(): invalid number of parameters"
201                exit 1
202        fi
203
204        local fichero=$1
205        local fecha=`date +%Y%m%d`
206
207        if [ ! -f $fichero ]; then
208                errorAndLog "${FUNCNAME}(): file $fichero doesn't exists"
209                return 1
210        fi
211
212        echoAndLog "${FUNCNAME}(): realizando backup de $fichero"
213
214        # realiza una copia de la última configuración como last
215        cp -p $fichero "${fichero}-LAST"
216
217        # si para el día no hay backup lo hace, sino no
218        if [ ! -f "${fichero}-${fecha}" ]; then
219                cp -p $fichero "${fichero}-${fecha}"
220        fi
221
222        echoAndLog "${FUNCNAME}(): backup realizado"
223}
224
225#####################################################################
226####### Funciones para el manejo de bases de datos
227#####################################################################
228
229# This function set password to root
230function mysqlSetRootPassword()
231{
232        if [ $# -ne 1 ]; then
233                errorAndLog "mysqlSetRootPassword(): invalid number of parameters"
234                exit 1
235        fi
236
237        local root_mysql=$1
238        echoAndLog "mysqlSetRootPassword(): setting root password in MySQL server"
239        /usr/bin/mysqladmin -u root password ${root_mysql}
240        if [ $? -ne 0 ]; then
241                errorAndLog "mysqlSetRootPassword(): error while setting root password in MySQL server"
242                return 1
243        fi
244        echoAndLog "mysqlSetRootPassword(): root password saved!"
245        return 0
246}
247
248# Si el servicio mysql esta ya instalado cambia la variable de la clave del root por la ya existente
249function mysqlGetRootPassword(){
250        local pass_mysql
251        local pass_mysql2
252        stty -echo
253        echo "Existe un servicio mysql ya instalado"
254        read -p  "Insertar clave de root de Mysql: " pass_mysql
255        echo ""
256        read -p "Confirmar clave:" pass_mysql2
257        echo ""
258        stty echo
259        if [ "$pass_mysql" == "$pass_mysql2" ] ;then
260                MYSQL_ROOT_PASSWORD=$pass_mysql
261                echo "La clave es: ${MYSQL_ROOT_PASSWORD}"
262                return 0
263        else
264                echo "Las claves no coinciden no se configura la clave del servidor de base de datos."
265                echo "las operaciones con la base de datos daran error"
266                return 1
267        fi
268
269
270}
271
272# comprueba si puede conectar con mysql con el usuario root
273function mysqlTestConnection()
274{
275        if [ $# -ne 1 ]; then
276                errorAndLog "mysqlTestConnection(): invalid number of parameters"
277                exit 1
278        fi
279
280        local root_password="${1}"
281        echoAndLog "mysqlTestConnection(): checking connection to mysql..."
282        echo "" | mysql -uroot -p"${root_password}"
283        if [ $? -ne 0 ]; then
284                errorAndLog "mysqlTestConnection(): connection to mysql failed, check root password and if daemon is running!"
285                return 1
286        else
287                echoAndLog "mysqlTestConnection(): connection success"
288                return 0
289        fi
290}
291
292# comprueba si la base de datos existe
293function mysqlDbExists()
294{
295        if [ $# -ne 2 ]; then
296                errorAndLog "mysqlDbExists(): invalid number of parameters"
297                exit 1
298        fi
299
300        local root_password="${1}"
301        local database=$2
302        echoAndLog "mysqlDbExists(): checking if $database exists..."
303        echo "show databases" | mysql -uroot -p"${root_password}" | grep "^${database}$"
304        if [ $? -ne 0 ]; then
305                echoAndLog "mysqlDbExists():database $database doesn't exists"
306                return 1
307        else
308                echoAndLog "mysqlDbExists():database $database exists"
309                return 0
310        fi
311}
312
313function mysqlCheckDbIsEmpty()
314{
315        if [ $# -ne 2 ]; then
316                errorAndLog "mysqlCheckDbIsEmpty(): invalid number of parameters"
317                exit 1
318        fi
319
320        local root_password="${1}"
321        local database=$2
322        echoAndLog "mysqlCheckDbIsEmpty(): checking if $database is empty..."
323        num_tablas=`echo "show tables" | mysql -uroot -p"${root_password}" "${database}" | wc -l`
324        if [ $? -ne 0 ]; then
325                errorAndLog "mysqlCheckDbIsEmpty(): error executing query, check database and root password"
326                exit 1
327        fi
328
329        if [ $num_tablas -eq 0 ]; then
330                echoAndLog "mysqlCheckDbIsEmpty():database $database is empty"
331                return 0
332        else
333                echoAndLog "mysqlCheckDbIsEmpty():database $database has tables"
334                return 1
335        fi
336
337}
338
339
340function mysqlImportSqlFileToDb()
341{
342        if [ $# -ne 3 ]; then
343                errorAndLog "${FNCNAME}(): invalid number of parameters"
344                exit 1
345        fi
346
347        local root_password="${1}"
348        local database=$2
349        local sqlfile=$3
350
351        if [ ! -f $sqlfile ]; then
352                errorAndLog "${FUNCNAME}(): Unable to locate $sqlfile!!"
353                return 1
354        fi
355
356        echoAndLog "${FUNCNAME}(): importing sql file to ${database}..."
357        perl -pi -e "s/SERVERIP/$SERVERIP/g; s/DEFAULTUSER/$OPENGNSYS_DB_DEFAULTUSER/g; s/DEFAULTPASSWD/$OPENGNSYS_DB_DEFAULTPASSWD/g" $sqlfile
358        mysql -uroot -p"${root_password}" "${database}" < $sqlfile
359        if [ $? -ne 0 ]; then
360                errorAndLog "${FUNCNAME}(): error while importing $sqlfile in database $database"
361                return 1
362        fi
363        echoAndLog "${FUNCNAME}(): file imported to database $database"
364        return 0
365}
366
367# Crea la base de datos
368function mysqlCreateDb()
369{
370        if [ $# -ne 2 ]; then
371                errorAndLog "${FUNCNAME}(): invalid number of parameters"
372                exit 1
373        fi
374
375        local root_password="${1}"
376        local database=$2
377
378        echoAndLog "${FUNCNAME}(): creating database..."
379        mysqladmin -u root --password="${root_password}" create $database
380        if [ $? -ne 0 ]; then
381                errorAndLog "${FUNCNAME}(): error while creating database $database"
382                return 1
383        fi
384        echoAndLog "${FUNCNAME}(): database $database created"
385        return 0
386}
387
388
389function mysqlCheckUserExists()
390{
391        if [ $# -ne 2 ]; then
392                errorAndLog "mysqlCheckUserExists(): invalid number of parameters"
393                exit 1
394        fi
395
396        local root_password="${1}"
397        local userdb=$2
398
399        echoAndLog "mysqlCheckUserExists(): checking if $userdb exists..."
400        echo "select user from user where user='${userdb}'\\G" |mysql -uroot -p"${root_password}" mysql | grep user
401        if [ $? -ne 0 ]; then
402                echoAndLog "mysqlCheckUserExists(): user doesn't exists"
403                return 1
404        else
405                echoAndLog "mysqlCheckUserExists(): user already exists"
406                return 0
407        fi
408
409}
410
411# Crea un usuario administrativo para la base de datos
412function mysqlCreateAdminUserToDb()
413{
414        if [ $# -ne 4 ]; then
415                errorAndLog "mysqlCreateAdminUserToDb(): invalid number of parameters"
416                exit 1
417        fi
418
419        local root_password=$1
420        local database=$2
421        local userdb=$3
422        local passdb=$4
423
424        echoAndLog "mysqlCreateAdminUserToDb(): creating admin user ${userdb} to database ${database}"
425
426        cat > $WORKDIR/create_${database}.sql <<EOF
427GRANT USAGE ON *.* TO '${userdb}'@'localhost' IDENTIFIED BY '${passdb}' ;
428GRANT ALL PRIVILEGES ON ${database}.* TO '${userdb}'@'localhost' WITH GRANT OPTION ;
429FLUSH PRIVILEGES ;
430EOF
431        mysql -u root --password=${root_password} < $WORKDIR/create_${database}.sql
432        if [ $? -ne 0 ]; then
433                errorAndLog "mysqlCreateAdminUserToDb(): error while creating user in mysql"
434                rm -f $WORKDIR/create_${database}.sql
435                return 1
436        else
437                echoAndLog "mysqlCreateAdminUserToDb(): user created ok"
438                rm -f $WORKDIR/create_${database}.sql
439                return 0
440        fi
441}
442
443
444#####################################################################
445####### Funciones para el manejo de Subversion
446#####################################################################
447
448function svnCheckoutCode()
449{
450        if [ $# -ne 1 ]; then
451                errorAndLog "${FUNCNAME}(): invalid number of parameters"
452                exit 1
453        fi
454
455        local url=$1
456
457        echoAndLog "${FUNCNAME}(): downloading subversion code..."
458
459        /usr/bin/svn co "${url}" opengnsys
460        if [ $? -ne 0 ]; then
461                errorAndLog "${FUNCNAME}(): error getting code from ${url}, verify your user and password"
462                return 1
463        fi
464        echoAndLog "${FUNCNAME}(): subversion code downloaded"
465        return 0
466}
467
468
469function svnExportCode()
470{
471        if [ $# -ne 1 ]; then
472                errorAndLog "${FUNCNAME}(): invalid number of parameters"
473                exit 1
474        fi
475
476        local url=$1
477
478        echoAndLog "${FUNCNAME}(): downloading subversion code..."
479
480        /usr/bin/svn export "${url}" opengnsys
481        if [ $? -ne 0 ]; then
482                errorAndLog "${FUNCNAME}(): error getting code from ${url}, verify your user and password"
483                return 1
484        fi
485        echoAndLog "${FUNCNAME}(): subversion code downloaded"
486        return 0
487}
488
489
490############################################################
491###  Detectar red
492############################################################
493
494function getNetworkSettings()
495{
496        # Variables globales definidas:
497        # - SERVERIP: IP local del servidor.
498        # - NETIP:    IP de la red.
499        # - NETMASK:  máscara de red.
500        # - NETBROAD: IP de difusión de la red.
501        # - ROUTERIP: IP del router.
502        # - DNSIP:    IP del servidor DNS.
503
504        echoAndLog "getNetworkSettings(): Detecting default network parameters."
505        SERVERIP=$(LANG=C ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | head -n1 | awk '{print $1}')
506        NETMASK=$(LANG=C ifconfig | grep 'Mask:'| grep -v '127.0.0.1' | cut -d: -f4 | head -n1 | awk '{print $1}')
507        NETBROAD=$(LANG=C ifconfig | grep 'Bcast:'| grep -v '127.0.0.1' | cut -d: -f3 | head -n1 | awk '{print $1}')
508        NETIP=$(netstat -r | grep $NETMASK | head -n1 | awk '{print $1}')
509        ROUTERIP=$(netstat -nr | awk '$1~/0\.0\.0\.0/ {print $2}')
510        DNSIP=$(awk '/nameserver/ {print $2}' /etc/resolv.conf | head -n1)
511        if [ -z "$NETIP" -o -z "$NETMASK" ]; then
512                errorAndLog "getNetworkSettings(): Network not detected."
513                exit 1
514        fi
515
516        # Variables de ejecución de Apache
517        # - APACHE_RUN_USER
518        # - APACHE_RUN_GROUP
519        if [ -f /etc/apache2/envvars ]; then
520                source /etc/apache2/envvars
521        fi
522        APACHE_RUN_USER=${APACHE_RUN_USER:-"www-data"}
523        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"www-data"}
524}
525
526
527############################################################
528### Esqueleto para el Servicio pxe y contenedor tftpboot ###
529############################################################
530
531function tftpConfigure() {
532        echo "Configurando el servicio tftp"
533        basetftp=/var/lib/tftpboot
534
535        # reiniciamos demonio internet ????? porque ????
536        /etc/init.d/openbsd-inetd start
537
538        # preparacion contenedor tftpboot
539        cp -pr /usr/lib/syslinux/ ${basetftp}/syslinux
540        cp /usr/lib/syslinux/pxelinux.0 ${basetftp}
541        # prepamos el directorio de la configuracion de pxe
542        mkdir -p ${basetftp}/pxelinux.cfg
543        cat > ${basetftp}/pxelinux.cfg/default <<EOF
544DEFAULT pxe
545
546LABEL pxe
547KERNEL linux
548APPEND initrd=initrd.gz ip=dhcp ro vga=788 irqpoll acpi=on
549EOF
550        # comprobamos el servicio tftp
551        sleep 1
552        testPxe
553        ## damos perfimos de lectura a usuario web.
554        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP ${basetftp}
555}
556
557function testPxe () {
558        cd /tmp
559        echo "comprobando servicio pxe ..... Espere"
560        tftp -v localhost -c get pxelinux.0 /tmp/pxelinux.0 && echo "servidor tftp OK" || echo "servidor tftp KO"
561        cd /
562}
563
564########################################################################
565## Configuracion servicio NFS
566########################################################################
567
568# function nfsConfigure ()
569# {
570#         echoAndLog "${FUNCNAME}(): Sample NFS Configuration."
571#         sed -e "s/NETIP/$NETIP/g" -e "s/NETMASK/$NETMASK/g" $WORKDIR/opengnsys/server/NFS/exports  >> /etc/exports
572#       /etc/init.d/nfs-kernel-server restart
573#       exportfs -va
574#         echoAndLog "${FUNCNAME}(): Sample NFS Configured in file \"/etc/exports\"."
575# }
576
577# ADVERTENCIA: usa variables globales NETIP y NETMASK!
578function nfsConfigure()
579{
580        echoAndLog "${FUNCNAME}(): Config nfs server."
581
582        backupFile /etc/exports
583
584        nfsAddExport /opt/opengnsys/client ${NETIP}/${NETMASK}:ro,no_subtree_check,no_root_squash,sync
585        if [ $? -ne 0 ]; then
586                errorAndLog "${FUNCNAME}(): error while adding nfs client config"
587                return 1
588        fi
589
590        nfsAddExport /opt/opengnsys/images ${NETIP}/${NETMASK}:rw,no_subtree_check,no_root_squash,sync,crossmnt
591        if [ $? -ne 0 ]; then
592                errorAndLog "${FUNCNAME}(): error while adding nfs images config"
593                return 1
594        fi
595
596        nfsAddExport /opt/opengnsys/log/clients ${NETIP}/${NETMASK}:rw,no_subtree_check,no_root_squash,sync
597        if [ $? -ne 0 ]; then
598                errorAndLog "${FUNCNAME}(): error while adding logging client config"
599                return 1
600        fi
601
602        /etc/init.d/nfs-kernel-server restart
603
604        exportfs -va
605        if [ $? -ne 0 ]; then
606                errorAndLog "${FUNCNAME}(): error while configure exports"
607                return 1
608        fi
609
610        echoAndLog "${FUNCNAME}(): Added NFS configuration to file \"/etc/exports\"."
611        return 0
612}
613
614
615# ejemplos:
616#nfsAddExport /opt/opengnsys 192.168.0.0/255.255.255.0:ro,no_subtree_check,no_root_squash,sync
617#nfsAddExport /opt/opengnsys 192.168.0.0/255.255.255.0
618#nfsAddExport /opt/opengnsys 80.20.2.1:ro 192.123.32.2:rw
619function nfsAddExport()
620{
621        if [ $# -lt 2 ]; then
622                errorAndLog "${FUNCNAME}(): invalid number of parameters"
623                exit 1
624        fi
625
626        if [ ! -f /etc/exports ]; then
627                errorAndLog "${FUNCNAME}(): /etc/exports don't exists"
628                return 1
629        fi
630
631        local export="${1}"
632        local contador=0
633        local cadenaexport
634
635        grep "^${export}" /etc/exports > /dev/null
636        if [ $? -eq 0 ]; then
637                echoAndLog "${FUNCNAME}(): $export exists in /etc/exports, omiting"
638                return 0
639        fi
640
641        cadenaexport="${export}"
642        for parametro in $*
643        do
644                if [ $contador -gt 0 ]
645                then
646                        host=`echo $parametro | awk -F: '{print $1}'`
647                        options=`echo $parametro | awk -F: '{print $2}'`
648                        if [ "${host}" == "" ]; then
649                                errorAndLog "${FUNCNAME}(): host can't be empty"
650                                return 1
651                        fi
652                        cadenaexport="${cadenaexport}\t${host}"
653
654                        if [ "${options}" != "" ]; then
655                                cadenaexport="${cadenaexport}(${options})"
656                        fi
657                fi
658                let contador=contador+1
659        done
660
661        echo -en "$cadenaexport\n" >> /etc/exports
662
663        echoAndLog "${FUNCNAME}(): add $export to /etc/exports"
664
665        return 0
666}
667
668########################################################################
669## Configuracion servicio DHCP
670########################################################################
671
672function dhcpConfigure()
673{
674        echoAndLog "${FUNCNAME}(): Sample DHCP Configuration."
675
676        backupFile /etc/dhcp3/dhcpd.conf
677
678        sed -e "s/SERVERIP/$SERVERIP/g" \
679            -e "s/NETIP/$NETIP/g" \
680            -e "s/NETMASK/$NETMASK/g" \
681            -e "s/NETBROAD/$NETBROAD/g" \
682            -e "s/ROUTERIP/$ROUTERIP/g" \
683            -e "s/DNSIP/$DNSIP/g" \
684            $WORKDIR/opengnsys/server/DHCP/dhcpd.conf > /etc/dhcp3/dhcpd.conf
685        if [ $? -ne 0 ]; then
686                errorAndLog "${FUNCNAME}(): error while configuring dhcp server"
687                return 1
688        fi
689
690        /etc/init.d/dhcp3-server restart
691        echoAndLog "${FUNCNAME}(): Sample DHCP Configured in file \"/etc/dhcp3/dhcpd.conf\"."
692        return 0
693}
694
695
696#####################################################################
697####### Funciones específicas de la instalación de Opengnsys
698#####################################################################
699
700# Copiar ficheros del OpenGNSys Web Console.
701function installWebFiles()
702{
703        echoAndLog "${FUNCNAME}(): Installing web files..."
704        cp -ar $WORKDIR/opengnsys/admin/WebConsole/* $INSTALL_TARGET/www   #*/ comentario para doxigen
705        if [ $? != 0 ]; then
706                errorAndLog "${FUNCNAME}(): Error copying web files."
707                exit 1
708        fi
709        find $INSTALL_TARGET/www -name .svn -type d -exec rm -fr {} \; 2>/dev/null
710        # Cambiar permisos para ficheros especiales.
711        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP \
712                        $INSTALL_TARGET/www/includes \
713                        $INSTALL_TARGET/www/comandos/gestores/filescripts \
714                        $INSTALL_TARGET/www/images/iconos
715        echoAndLog "${FUNCNAME}(): Web files installed successfully."
716}
717
718# Configuración específica de Apache.
719function openGnsysInstallWebConsoleApacheConf()
720{
721        if [ $# -ne 2 ]; then
722                errorAndLog "${FUNCNAME}(): invalid number of parameters"
723                exit 1
724        fi
725
726        local path_opengnsys_base=$1
727        local path_apache2_confd=$2
728        local path_web_console=${path_opengnsys_base}/www
729
730        if [ ! -d $path_apache2_confd ]; then
731                errorAndLog "${FUNCNAME}(): path to apache2 conf.d can not found, verify your server installation"
732                return 1
733        fi
734
735        mkdir -p $path_apache2_confd/{sites-available,sites-enabled}
736
737        echoAndLog "${FUNCNAME}(): creating apache2 config file.."
738
739        # genera configuración
740        cat > $path_opengnsys_base/etc/apache.conf <<EOF
741# OpenGNSys Web Console configuration for Apache
742
743Alias /opengnsys ${path_web_console}
744
745<Directory ${path_web_console}>
746        Options -Indexes FollowSymLinks
747        DirectoryIndex acceso.php
748</Directory>
749EOF
750
751        ln -fs $path_opengnsys_base/etc/apache.conf $path_apache2_confd/sites-available/opengnsys.conf
752        ln -fs $path_apache2_confd/sites-available/opengnsys.conf $path_apache2_confd/sites-enabled/opengnsys.conf
753        if [ $? -ne 0 ]; then
754                errorAndLog "${FUNCNAME}(): config file can't be linked to apache conf, verify your server installation"
755                return 1
756        else
757                echoAndLog "${FUNCNAME}(): config file created and linked, restarting apache daemon"
758                /etc/init.d/apache2 restart
759                return 0
760        fi
761}
762
763# Crea la estructura base de la instalación de opengnsys
764function openGnsysInstallCreateDirs()
765{
766        if [ $# -ne 1 ]; then
767                errorAndLog "${FUNCNAME}(): invalid number of parameters"
768                exit 1
769        fi
770
771        local path_opengnsys_base=$1
772
773        echoAndLog "${FUNCNAME}(): creating directory paths in $path_opengnsys_base"
774
775        mkdir -p $path_opengnsys_base
776        mkdir -p $path_opengnsys_base/admin/{autoexec,comandos,menus,usuarios}
777        mkdir -p $path_opengnsys_base/bin
778        mkdir -p $path_opengnsys_base/client
779        mkdir -p $path_opengnsys_base/etc
780        mkdir -p $path_opengnsys_base/lib
781        mkdir -p $path_opengnsys_base/log/clients
782        mkdir -p $path_opengnsys_base/sbin
783        mkdir -p $path_opengnsys_base/www
784        mkdir -p $path_opengnsys_base/images
785        ln -fs /var/lib/tftpboot $path_opengnsys_base
786        ln -fs $path_opengnsys_base/log /var/log/opengnsys
787
788        if [ $? -ne 0 ]; then
789                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
790                return 1
791        fi
792
793        echoAndLog "${FUNCNAME}(): directory paths created"
794        return 0
795}
796
797# Copia ficheros de configuración y ejecutables genéricos del servidor.
798function openGnsysCopyServerFiles () {
799        if [ $# -ne 1 ]; then
800                errorAndLog "${FUNCNAME}(): invalid number of parameters"
801                exit 1
802        fi
803
804        local path_opengnsys_base=$1
805
806        local SOURCES=( client/boot/initrd-generator \
807                        client/boot/upgrade-clients-udeb.sh \
808                        client/boot/udeblist.conf  \
809                        client/boot/udeblist-jaunty.conf  \
810                        client/boot/udeblist-karmic.conf \
811                        server/PXE/pxelinux.cfg/default )
812        local TARGETS=( bin/initrd-generator \
813                        bin/upgrade-clients-udeb.sh \
814                        etc/udeblist.conf \
815                        etc/udeblist-jaunty.conf  \
816                        etc/udeblist-karmic.conf \
817                        tftpboot/pxelinux.cfg/default )
818
819        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
820                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
821                exit 1
822        fi
823
824        echoAndLog "${FUNCNAME}(): copying files to server directories"
825
826        pushd $WORKDIR/opengnsys
827        local i
828        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
829                if [ -f "${SOURCES[$i]}" ]; then
830                        echoAndLog "Copying ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
831                        cp -p "${SOURCES[$i]}" "${path_opengnsys_base}/${TARGETS[$i]}"
832                fi
833                if [ -d "${SOURCES[$i]}" ]; then
834                        echoAndLog "Copying content of ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
835                        cp -ar "${SOURCES[$i]}/*" "${path_opengnsys_base}/${TARGETS[$i]}"
836                fi
837        done
838        popd
839}
840
841####################################################################
842### Funciones de compilación de códifo fuente de servicios
843####################################################################
844
845# Compilar los servicios de OpenGNsys
846function servicesCompilation ()
847{
848        local hayErrores=0
849
850        # Compilar OpenGNSys Server
851        echoAndLog "${FUNCNAME}(): Compiling OpenGNSys Admin Server"
852        pushd $WORKDIR/opengnsys/admin/Services/ogAdmServer
853        make && make install
854        if [ $? -ne 0 ]; then
855                echoAndLog "${FUNCNAME}(): error while compiling OpenGNSys Admin Server"
856                hayErrores=1
857        fi
858        popd
859        # Compilar OpenGNSys Repository Manager
860        echoAndLog "${FUNCNAME}(): Compiling OpenGNSys Repository Manager"
861        pushd $WORKDIR/opengnsys/admin/Services/ogAdmRepo
862        make && make install
863        if [ $? -ne 0 ]; then
864                echoAndLog "${FUNCNAME}(): error while compiling OpenGNSys Repository Manager"
865                hayErrores=1
866        fi
867        popd
868        # Compilar OpenGNSys Client
869        echoAndLog "${FUNCNAME}(): Compiling OpenGNSys Admin Client"
870        pushd $WORKDIR/opengnsys/admin/Services/ogAdmClient
871        make && mv ogAdmClient ../../../client/nfsexport/bin
872        if [ $? -ne 0 ]; then
873                echoAndLog "${FUNCNAME}(): error while compiling OpenGNSys Admin Client"
874                hayErrores=1
875        fi
876        popd
877
878        return $hayErrores
879}
880
881
882####################################################################
883### Funciones instalacion cliente opengnsys
884####################################################################
885
886function openGnsysClientCreate()
887{
888        local OSDISTRIB OSCODENAME
889
890        local hayErrores=0
891
892        echoAndLog "${FUNCNAME}(): Copying OpenGNSys Client files."
893        cp -ar $WORKDIR/opengnsys/client/nfsexport/* $INSTALL_TARGET/client
894        find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null
895        echoAndLog "${FUNCNAME}(): Copying OpenGNSys Cloning Engine files."
896        mkdir -p $INSTALL_TARGET/client/lib/engine/bin
897        cp -ar $WORKDIR/opengnsys/client/engine/*.lib $INSTALL_TARGET/client/lib/engine/bin
898        if [ $? -ne 0 ]; then
899                errorAndLog "${FUNCNAME}(): error while copying engine files"
900                hayErrores=1
901        fi
902
903        # Cargar Kernel, Initrd y paquetes udeb para la distribución del servidor (o por defecto).
904        OSDISTRIB=$(lsb_release -i | awk -F: '{sub(/\t/,""); print $2}') 2>/dev/null
905        OSCODENAME=$(lsb_release -c | awk -F: '{sub(/\t/,""); print $2}') 2>/dev/null
906        if [ "$OSDISTRIB" = "Ubuntu" -a -n "$OSCODENAME" ]; then
907                echoAndLog "${FUNCNAME}(): Loading Kernel and Initrd files for $OSDISTRIB $OSCODENAME."
908                $INSTALL_TARGET/bin/initrd-generator -t $INSTALL_TARGET/tftpboot -v "$OSCODENAME"
909                if [ $? -ne 0 ]; then
910                        errorAndLog "${FUNCNAME}(): error while generating initrd OpenGNSys Admin Client"
911                        hayErrores=1
912                fi
913                echoAndLog "${FUNCNAME}(): Loading udeb files for $OSDISTRIB $OSCODENAME."
914                $INSTALL_TARGET/bin/upgrade-clients-udeb.sh "$OSCODENAME"
915                if [ $? -ne 0 ]; then
916                        errorAndLog "${FUNCNAME}(): error while upgrading udeb files OpenGNSys Admin Client"
917                        hayErrores=1
918                fi
919        else
920                echoAndLog "${FUNCNAME}(): Loading default Kernel and Initrd files."
921                $INSTALL_TARGET/bin/initrd-generator -t $INSTALL_TARGET/tftpboot/
922                if [ $? -ne 0 ]; then
923                        errorAndLog "${FUNCNAME}(): error while generating initrd OpenGNSys Admin Client"
924                        hayErrores=1
925                fi
926                echoAndLog "${FUNCNAME}(): Loading default udeb files."
927                $INSTALL_TARGET/bin/upgrade-clients-udeb.sh
928                if [ $? -ne 0 ]; then
929                        errorAndLog "${FUNCNAME}(): error while upgrading udeb files OpenGNSys Admin Client"
930                        hayErrores=1
931                fi
932        fi
933
934        if [ $hayErrores -eq 0 ]; then
935                echoAndLog "${FUNCNAME}(): Client generation success."
936        else
937                errorAndLog "${FUNCNAME}(): Client generation with errors"
938        fi
939
940        return $hayErrores
941}
942
943
944# Configuración básica de servicios de OpenGNSys
945function openGnsysConfigure()
946{
947        echoAndLog "openGnsysConfigure(): Copying init files."
948        cp -p $WORKDIR/opengnsys/admin/Services/opengnsys.init /etc/init.d/opengnsys
949        cp -p $WORKDIR/opengnsys/admin/Services/opengnsys.default /etc/default/opengnsys
950        update-rc.d opengnsys defaults
951        echoAndLog "openGnsysConfigure(): Creating OpenGNSys config file in \"$INSTALL_TARGET/etc\"."
952        perl -pi -e "s/SERVERIP/$SERVERIP/g" $INSTALL_TARGET/etc/ogAdmServer.cfg
953        perl -pi -e "s/SERVERIP/$SERVERIP/g" $INSTALL_TARGET/etc/ogAdmRepo.cfg
954        echoAndLog "${FUNCNAME}(): Creating Web Console config file"
955        OPENGNSYS_CONSOLEURL="http://$SERVERIP/opengnsys"
956        perl -pi -e "s/SERVERIP/$SERVERIP/g; s/OPENGNSYSURL/${OPENGNSYS_CONSOLEURL//\//\\/}/g" $INSTALL_TARGET/www/controlacceso.php
957        sed -e "s/SERVERIP/$SERVERIP/g" -e "s/OPENGNSYSURL/${OPENGNSYS_CONSOLEURL//\//\\/}/g" $WORKDIR/opengnsys/admin/Services/ogAdmClient/ogAdmClient.cfg > $INSTALL_TARGET/client/etc/ogAdmClient.cfg
958        echoAndLog "openGnsysConfiguration(): Starting OpenGNSys services."
959        /etc/init.d/opengnsys start
960}
961
962
963#####################################################################
964#######  Función de resumen informativo de la instalación
965#####################################################################
966
967function installationSummary(){
968        echo
969        echoAndLog "OpenGNSys Installation Summary"
970        echo       "=============================="
971        echoAndLog "OpenGNSys installation directory: $INSTALL_TARGET"
972        echoAndLog "OpenGNSys repository directory:   $INSTALL_TARGET/images"
973        echoAndLog "TFTP configuracion directory:     /var/lib/tftpboot"
974        echoAndLog "DHCP configuracion file:          /etc/dhcp3/dhcpd.conf"
975        echoAndLog "NFS configuracion file:           /etc/exports"
976        echoAndLog "OpenGNSys Web Console URL:        $OPENGNSYS_CONSOLEURL"
977        echoAndLog "Web Console admin user:           $OPENGNSYS_DB_USER"
978        echoAndLog "Web Console admin password:       $OPENGNSYS_DB_PASSWD"
979        echoAndLog "Web Console default user:         $OPENGNSYS_DB_DEFAULTUSER"
980        echoAndLog "Web Console default password:     $OPENGNSYS_DB_DEFAULTPASSWD"
981        echo
982        echoAndLog "Post-Installation Instructions:"
983        echo       "==============================="
984        echoAndLog "Review or edit all configuration files."
985        echoAndLog "Insert DHCP configuration data and restart service."
986        echoAndLog "Log-in as Web Console admin user."
987        echoAndLog " - Review default Organization data and default user."
988        echoAndLog "Log-in as Web Console organization user."
989        echoAndLog " - Insert OpenGNSys data (rooms, computers, etc)."
990echo
991}
992
993
994
995#####################################################################
996####### Proceso de instalación de OpenGNSys
997#####################################################################
998
999
1000echoAndLog "OpenGNSys installation begins at $(date)"
1001
1002# Detectar parámetros de red por defecto
1003getNetworkSettings
1004if [ $? -ne 0 ]; then
1005        errorAndLog "Error reading default network settings."
1006        exit 1
1007fi
1008
1009# Actualizar repositorios
1010apt-get update
1011
1012# Instalación de dependencias (paquetes de sistema operativo).
1013declare -a notinstalled
1014checkDependencies DEPENDENCIES notinstalled
1015if [ $? -ne 0 ]; then
1016        installDependencies notinstalled
1017        if [ $? -ne 0 ]; then
1018                echoAndLog "Error while installing some dependeces, please verify your server installation before continue"
1019                exit 1
1020        fi
1021fi
1022
1023# Arbol de directorios de OpenGNSys.
1024openGnsysInstallCreateDirs ${INSTALL_TARGET}
1025if [ $? -ne 0 ]; then
1026        errorAndLog "Error while creating directory paths!"
1027        exit 1
1028fi
1029
1030# Descarga del repositorio de código en directorio temporal
1031#svnCheckoutCode $SVN_URL
1032svnExportCode $SVN_URL
1033if [ $? -ne 0 ]; then
1034        errorAndLog "Error while getting code from svn"
1035        exit 1
1036fi
1037
1038# Compilar código fuente de los servicios de OpenGNSys.
1039servicesCompilation
1040if [ $? -ne 0 ]; then
1041        errorAndLog "Error while compiling OpenGnsys services"
1042        exit 1
1043fi
1044
1045# Configurando tftp
1046tftpConfigure
1047
1048# Configuración NFS
1049nfsConfigure
1050if [ $? -ne 0 ]; then
1051        errorAndLog "Error while configuring nfs server!"
1052        exit 1
1053fi
1054
1055# Configuración ejemplo DHCP
1056dhcpConfigure
1057if [ $? -ne 0 ]; then
1058        errorAndLog "Error while copying your dhcp server files!"
1059        exit 1
1060fi
1061
1062# Copiar ficheros de servicios OpenGNSys Server.
1063openGnsysCopyServerFiles ${INSTALL_TARGET}
1064if [ $? -ne 0 ]; then
1065        errorAndLog "Error while copying the server files!"
1066        exit 1
1067fi
1068
1069# Instalar Base de datos de OpenGNSys Admin.
1070isInArray notinstalled "mysql-server"
1071if [ $? -eq 0 ]; then
1072        mysqlSetRootPassword ${MYSQL_ROOT_PASSWORD}
1073else
1074        mysqlGetRootPassword
1075
1076fi
1077
1078mysqlTestConnection ${MYSQL_ROOT_PASSWORD}
1079if [ $? -ne 0 ]; then
1080        errorAndLog "Error while connection to mysql"
1081        exit 1
1082fi
1083mysqlDbExists ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DATABASE}
1084if [ $? -ne 0 ]; then
1085        echoAndLog "Creating Web Console database"
1086        mysqlCreateDb ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DATABASE}
1087        if [ $? -ne 0 ]; then
1088                errorAndLog "Error while creating Web Console database"
1089                exit 1
1090        fi
1091else
1092        echoAndLog "Web Console database exists, ommiting creation"
1093fi
1094
1095mysqlCheckUserExists ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DB_USER}
1096if [ $? -ne 0 ]; then
1097        echoAndLog "Creating user in database"
1098        mysqlCreateAdminUserToDb ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DATABASE} ${OPENGNSYS_DB_USER} "${OPENGNSYS_DB_PASSWD}"
1099        if [ $? -ne 0 ]; then
1100                errorAndLog "Error while creating database user"
1101                exit 1
1102        fi
1103
1104fi
1105
1106mysqlCheckDbIsEmpty ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DATABASE}
1107if [ $? -eq 0 ]; then
1108        echoAndLog "Creating tables..."
1109        if [ -f $WORKDIR/$OPENGNSYS_DB_CREATION_FILE ]; then
1110                mysqlImportSqlFileToDb ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_CREATION_FILE
1111        else
1112                errorAndLog "Unable to locate $WORKDIR/$OPENGNSYS_DB_CREATION_FILE!!"
1113                exit 1
1114        fi
1115fi
1116
1117# copiando paqinas web
1118installWebFiles
1119
1120# creando configuracion de apache2
1121openGnsysInstallWebConsoleApacheConf $INSTALL_TARGET /etc/apache2
1122if [ $? -ne 0 ]; then
1123        errorAndLog "Error configuring Apache for OpenGNSYS Admin"
1124        exit 1
1125fi
1126
1127popd
1128
1129# Creando la estructura del cliente
1130openGnsysClientCreate
1131if [ $? -ne 0 ]; then
1132        errorAndLog "Error creating clients"
1133        exit 1
1134fi
1135
1136# Configuración de servicios de OpenGNSys
1137openGnsysConfigure
1138
1139# Mostrar sumario de la instalación e instrucciones de post-instalación.
1140installationSummary
1141
1142#rm -rf $WORKDIR
1143echoAndLog "OpenGNSys installation finished at $(date)"
1144
Note: See TracBrowser for help on using the repository browser.