source: installer/opengnsys_installer.sh @ 0fb7e9f

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 0fb7e9f was 89179ff, checked in by ramon <ramongomez@…>, 13 years ago

Instalador vversión 1.0.2: incluir URLs en variables (modifica #446).

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

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