source: installer/opengnsys_installer_v1.0.2.sh @ cd95622

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 cd95622 was f3b1480, checked in by ramon <ramongomez@…>, 14 years ago

Versión 1.0.2: mejoras en el instalador y nuevo script para cambio de clave Samba (modifica #428).

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

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