source: installer/opengnsys_installer_v1.0.2.sh @ 653c64e

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

Versión 1.0.2: instalador permite configurar el acceso a Samba.

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

  • Property mode set to 100755
File size: 43.1 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        else
762                SAMBAUSER="opengnsys"           # Usuario por defecto.
763                SAMBAPASS="og"                  # Clave por defecto.
764        fi
765        echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | smbpasswd -a -s $SAMBAUSER
766
767        # Editar la parte de acceso del cliente:
768        #    descomprimir Initrd, sustituir clave y recomprimir Initrd).
769        echoAndLog "${FUNCNAME}(): Configuring Samba client access."
770        mkdir -p $CLIENTDIR
771        pushd $CLIENTDIR 2>/dev/null
772        gzip -dc $CLIENTINITRD | cpio -im
773        sed -i "s/OPTIONS=\(.*\)user=\w*\(.*\)pass=\w*\(.*\)/OPTIONS=\1user=$SAMBAUSER\2pass=$SAMBAPASS\3/" scripts/ogfunctions
774        find . | cpio -H newc -oa | gzip -9c > $CLIENTINITRD
775        popd 2>/dev/null
776        rm -fr $CLIENTDIR
777
778        echoAndLog "${FUNCNAME}(): Added Samba configuration."
779        return 0
780}
781
782
783########################################################################
784## Configuracion servicio DHCP
785########################################################################
786
787function dhcpConfigure()
788{
789        echoAndLog "${FUNCNAME}(): Sample DHCP configuration."
790
791        local errcode=0
792        local i=0
793        local dev=""
794
795        backupFile $DHCPCFGDIR/dhcpd.conf
796        for dev in ${DEVICE[*]}; do
797                if [ -n "${SERVERIP[$i]}" ]; then
798                        backupFile $DHCPCFGDIR/dhcpd-$dev.conf
799                        sed -e "s/SERVERIP/${SERVERIP[$i]}/g" \
800                            -e "s/NETIP/${NETIP[$i]}/g" \
801                            -e "s/NETMASK/${NETMASK[$i]}/g" \
802                            -e "s/NETBROAD/${NETBROAD[$i]}/g" \
803                            -e "s/ROUTERIP/${ROUTERIP[$i]}/g" \
804                            -e "s/DNSIP/$DNSIP/g" \
805                            $WORKDIR/opengnsys/server/etc/dhcpd.conf.tmpl > $DHCPCFGDIR/dhcpd-$dev.conf || errcode=1
806                fi
807                let i++
808        done
809        if [ $errcode -ne 0 ]; then
810                errorAndLog "${FUNCNAME}(): error while configuring DHCP server"
811                return 1
812        fi
813        ln -f $DHCPCFGDIR/dhcpd-$DEFAULTDEV.conf $DHCPCFGDIR/dhcpd.conf
814        $DHCPINIT restart
815        echoAndLog "${FUNCNAME}(): Sample DHCP configured in \"$DHCPCFGDIR\"."
816        return 0
817}
818
819
820#####################################################################
821####### Funciones específicas de la instalación de Opengnsys
822#####################################################################
823
824# Copiar ficheros del OpenGnSys Web Console.
825function installWebFiles()
826{
827        echoAndLog "${FUNCNAME}(): Installing web files..."
828        cp -ar $WORKDIR/opengnsys/admin/WebConsole/* $INSTALL_TARGET/www   #*/ comentario para doxigen
829        if [ $? != 0 ]; then
830                errorAndLog "${FUNCNAME}(): Error copying web files."
831                exit 1
832        fi
833        find $INSTALL_TARGET/www -name .svn -type d -exec rm -fr {} \; 2>/dev/null
834        # Descomprimir XAJAX.
835        unzip -q -o $WORKDIR/opengnsys/admin/xajax_0.5_standard.zip -d $INSTALL_TARGET/www/xajax
836        # Cambiar permisos para ficheros especiales.
837        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/images/iconos
838        echoAndLog "${FUNCNAME}(): Web files installed successfully."
839}
840
841# Configuración específica de Apache.
842function openGnsysInstallWebConsoleApacheConf()
843{
844        if [ $# -ne 2 ]; then
845                errorAndLog "${FUNCNAME}(): invalid number of parameters"
846                exit 1
847        fi
848
849        local path_opengnsys_base=$1
850        local path_apache2_confd=$2
851        local path_web_console=${path_opengnsys_base}/www
852
853        if [ ! -d $path_apache2_confd ]; then
854                errorAndLog "${FUNCNAME}(): path to apache2 conf.d can not found, verify your server installation"
855                return 1
856        fi
857
858        mkdir -p $path_apache2_confd/{sites-available,sites-enabled}
859
860        echoAndLog "${FUNCNAME}(): creating apache2 config file.."
861
862
863        # genera configuración
864        cat > $path_opengnsys_base/etc/apache.conf <<EOF
865# OpenGnSys Web Console configuration for Apache
866
867Alias /opengnsys ${path_web_console}
868
869<Directory ${path_web_console}>
870        Options -Indexes FollowSymLinks
871        DirectoryIndex acceso.php
872</Directory>
873EOF
874
875        ln -fs $path_opengnsys_base/etc/apache.conf $path_apache2_confd/sites-available/opengnsys.conf
876        ln -fs $path_apache2_confd/sites-available/opengnsys.conf $path_apache2_confd/sites-enabled/opengnsys.conf
877        if [ $? -ne 0 ]; then
878                errorAndLog "${FUNCNAME}(): config file can't be linked to apache conf, verify your server installation"
879                return 1
880        else
881                echoAndLog "${FUNCNAME}(): config file created and linked, restarting apache daemon"
882                $APACHEINIT restart
883                return 0
884        fi
885}
886
887
888# Crear documentación Doxygen para la consola web.
889function makeDoxygenFiles()
890{
891        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
892        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
893                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
894        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
895                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
896                return 1
897        fi
898        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
899        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/api
900        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
901}
902
903
904# Crea la estructura base de la instalación de opengnsys
905function createDirs()
906{
907        if [ $# -ne 1 ]; then
908                errorAndLog "${FUNCNAME}(): invalid number of parameters"
909                exit 1
910        fi
911
912        local path_opengnsys_base="$1"
913
914        # Crear estructura de directorios.
915        echoAndLog "${FUNCNAME}(): creating directory paths in $path_opengnsys_base"
916        mkdir -p $path_opengnsys_base
917        mkdir -p $path_opengnsys_base/bin
918        mkdir -p $path_opengnsys_base/client
919        mkdir -p $path_opengnsys_base/doc
920        mkdir -p $path_opengnsys_base/etc
921        mkdir -p $path_opengnsys_base/lib
922        mkdir -p $path_opengnsys_base/log/clients
923        ln -fs $path_opengnsys_base/log /var/log/opengnsys
924        mkdir -p $path_opengnsys_base/sbin
925        mkdir -p $path_opengnsys_base/www
926        mkdir -p $path_opengnsys_base/images
927        ln -fs /var/lib/tftpboot $path_opengnsys_base
928        mkdir -p $path_opengnsys_base/tftpboot/pxelinux.cfg
929        mkdir -p $path_opengnsys_base/tftpboot/menu.lst
930        if [ $? -ne 0 ]; then
931                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
932                return 1
933        fi
934
935        # Crear usuario ficticio.
936        if id -u $OPENGNSYS_CLIENT_USER &>/dev/null; then
937                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENT_USER\" is already created"
938        else
939                echoAndLog "${FUNCNAME}(): creating OpenGnSys user"
940                useradd $OPENGNSYS_CLIENT_USER 2>/dev/null
941                if [ $? -ne 0 ]; then
942                        errorAndLog "${FUNCNAME}(): error creating OpenGnSys user"
943                        return 1
944                fi
945        fi
946
947        # Establecer los permisos básicos.
948        echoAndLog "${FUNCNAME}(): setting directory permissions"
949        chmod -R 775 $path_opengnsys_base/{log/clients,images}
950        chown -R :$OPENGNSYS_CLIENT_USER $path_opengnsys_base/{log/clients,images}
951        if [ $? -ne 0 ]; then
952                errorAndLog "${FUNCNAME}(): error while setting permissions"
953                return 1
954        fi
955
956        echoAndLog "${FUNCNAME}(): directory paths created"
957        return 0
958}
959
960# Copia ficheros de configuración y ejecutables genéricos del servidor.
961function copyServerFiles ()
962{
963        if [ $# -ne 1 ]; then
964                errorAndLog "${FUNCNAME}(): invalid number of parameters"
965                exit 1
966        fi
967
968        local path_opengnsys_base="$1"
969
970        local SOURCES=( server/tftpboot \
971                        server/bin \
972                        repoman/bin \
973                        installer/opengnsys_uninstall.sh \
974                        installer/opengnsys_update.sh \
975                        doc )
976        local TARGETS=( tftpboot \
977                        bin \
978                        bin \
979                        lib \
980                        lib \
981                        doc )
982
983        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
984                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
985                exit 1
986        fi
987
988        echoAndLog "${FUNCNAME}(): copying files to server directories"
989
990        pushd $WORKDIR/opengnsys
991        local i
992        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
993                if [ -f "${SOURCES[$i]}" ]; then
994                        echoAndLog "Copying ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
995                        cp -a "${SOURCES[$i]}" "${path_opengnsys_base}/${TARGETS[$i]}"
996                elif [ -d "${SOURCES[$i]}" ]; then
997                        echoAndLog "Copying content of ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
998                        cp -a "${SOURCES[$i]}"/* "${path_opengnsys_base}/${TARGETS[$i]}"
999        else
1000                        echoAndLog "Warning: Unable to copy ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1001                fi
1002        done
1003        popd
1004}
1005
1006####################################################################
1007### Funciones de compilación de código fuente de servicios
1008####################################################################
1009
1010# Compilar los servicios de OpenGnSys
1011function servicesCompilation ()
1012{
1013        local hayErrores=0
1014
1015        # Compilar OpenGnSys Server
1016        echoAndLog "${FUNCNAME}(): Compiling OpenGnSys Admin Server"
1017        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
1018        make && mv ogAdmServer $INSTALL_TARGET/sbin
1019        if [ $? -ne 0 ]; then
1020                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Admin Server"
1021                hayErrores=1
1022        fi
1023        popd
1024        # Compilar OpenGnSys Repository Manager
1025        echoAndLog "${FUNCNAME}(): Compiling OpenGnSys Repository Manager"
1026        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo
1027        make && mv ogAdmRepo $INSTALL_TARGET/sbin
1028        if [ $? -ne 0 ]; then
1029                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Repository Manager"
1030                hayErrores=1
1031        fi
1032        popd
1033        # Compilar OpenGnSys Agent
1034        echoAndLog "${FUNCNAME}(): Compiling OpenGnSys Agent"
1035        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
1036        make && mv ogAdmAgent $INSTALL_TARGET/sbin
1037        if [ $? -ne 0 ]; then
1038                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Agent"
1039                hayErrores=1
1040        fi
1041        popd   
1042        # Compilar OpenGnSys Client
1043        echoAndLog "${FUNCNAME}(): Compiling OpenGnSys Admin Client"
1044        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
1045        make && mv ogAdmClient ../../../../client/shared/bin
1046        if [ $? -ne 0 ]; then
1047                echoAndLog "${FUNCNAME}(): error while compiling OpenGnSys Admin Client"
1048                hayErrores=1
1049        fi
1050        popd
1051
1052        return $hayErrores
1053}
1054
1055####################################################################
1056### Funciones de copia de la Interface de administración
1057####################################################################
1058
1059# Copiar carpeta de Interface
1060function copyInterfaceAdm ()
1061{
1062        local hayErrores=0
1063       
1064        # Crear carpeta y copiar Interface
1065        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
1066        cp -ar $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client/interfaceAdm
1067        if [ $? -ne 0 ]; then
1068                echoAndLog "${FUNCNAME}(): error while copying Administration Interface Folder"
1069                hayErrores=1
1070        fi
1071        chown $OPENGNSYS_CLIENT_USER:$OPENGNSYS_CLIENT_USER $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
1072        chmod 700 $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
1073
1074        return $hayErrores
1075}
1076
1077####################################################################
1078### Funciones instalacion cliente opengnsys
1079####################################################################
1080
1081function copyClientFiles()
1082{
1083        local errstatus=0
1084
1085        echoAndLog "${FUNCNAME}(): Copying OpenGnSys Client files."
1086        cp -ar $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
1087        if [ $? -ne 0 ]; then
1088                errorAndLog "${FUNCNAME}(): error while copying client estructure"
1089                errstatus=1
1090        fi
1091        find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null
1092       
1093        echoAndLog "${FUNCNAME}(): Copying OpenGnSys Cloning Engine files."
1094        mkdir -p $INSTALL_TARGET/client/lib/engine/bin
1095        cp -ar $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
1096        if [ $? -ne 0 ]; then
1097                errorAndLog "${FUNCNAME}(): error while copying engine files"
1098                errstatus=1
1099        fi
1100       
1101        if [ $errstatus -eq 0 ]; then
1102                echoAndLog "${FUNCNAME}(): client copy files success."
1103        else
1104                errorAndLog "${FUNCNAME}(): client copy files with errors"
1105        fi
1106
1107        return $errstatus
1108}
1109
1110
1111# Crear cliente OpenGnSys 1.0
1112function clientCreate()
1113{
1114        local DOWNLOADURL="http://www.opengnsys.es/downloads"
1115        local FILENAME=ogclient-1.0.2-natty-32bit-beta01-rev2111.iso
1116        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
1117        local TMPDIR=/tmp/${FILENAME%.iso}
1118
1119        echoAndLog "${FUNCNAME}(): Loading Client"
1120        # Descargar, montar imagen, copiar cliente ogclient y desmontar.
1121        wget $DOWNLOADURL/$FILENAME -O $TARGETFILE
1122        if [ ! -s $TARGETFILE ]; then
1123                errorAndLog "${FUNCNAME}(): Error loading OpenGnSys Client"
1124                return 1
1125        fi
1126        echoAndLog "${FUNCNAME}(): Copying Client files"
1127        mkdir -p $TMPDIR
1128        mount -o loop,ro $TARGETFILE $TMPDIR
1129        if [ $? != 0 ]; then
1130                errorAndLog "${FUNCNAME}(): Unable to mount OpenGnSys Client image"
1131                return 1
1132        fi
1133        cp -vr $TMPDIR/ogclient $INSTALL_TARGET/tftpboot
1134        umount $TMPDIR
1135        rmdir $TMPDIR
1136
1137        # Establecer los permisos.
1138        find -L $INSTALL_TARGET/tftpboot -type d -exec chmod 755 {} \;
1139        find -L $INSTALL_TARGET/tftpboot -type f -exec chmod 644 {} \;
1140        chown -R :$OPENGNSYS_CLIENT_USER $INSTALL_TARGET/tftpboot/ogclient
1141        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/tftpboot/{menu.lst,pxelinux.cfg}
1142        echoAndLog "${FUNCNAME}(): Client generation success"
1143}
1144
1145
1146# Configuración básica de servicios de OpenGnSys
1147function openGnsysConfigure()
1148{
1149        local i=0
1150        local dev=""
1151
1152        echoAndLog "${FUNCNAME}(): Copying init files."
1153        cp -p $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
1154        cp -p $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default /etc/default/opengnsys
1155        cp -p $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepoAux /opt/opengnsys/sbin/
1156        eval $OGACTIVATE
1157        echoAndLog "${FUNCNAME}(): Creating cron files."
1158        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
1159        echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
1160
1161        echoAndLog "${FUNCNAME}(): Creating logrotate configuration file."
1162        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1163                $WORKDIR/opengnsys/server/etc/logrotate.tmpl > /etc/logrotate.d/opengnsys
1164
1165        echoAndLog "${FUNCNAME}(): Creating OpenGnSys config files."
1166        for dev in ${DEVICE[*]}; do
1167                if [ -n "${SERVERIP[i]}" ]; then
1168                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1169                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1170                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1171                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1172                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer/ogAdmServer.cfg > $INSTALL_TARGET/etc/ogAdmServer-$dev.cfg
1173                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1174                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo/ogAdmRepo.cfg > $INSTALL_TARGET/etc/ogAdmRepo-$dev.cfg
1175                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1176                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1177                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1178                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1179                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent/ogAdmAgent.cfg > $INSTALL_TARGET/etc/ogAdmAgent-$dev.cfg
1180                        OPENGNSYS_CONSOLEURL="http://${SERVERIP[i]}/opengnsys"
1181                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1182                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1183                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1184                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1185                            -e "s/OPENGNSYSURL/${OPENGNSYS_CONSOLEURL//\//\\/}/g" \
1186                                $INSTALL_TARGET/www/controlacceso.php > $INSTALL_TARGET/www/controlacceso-$dev.php
1187                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1188                            -e "s/OPENGNSYSURL/${OPENGNSYS_CONSOLEURL//\//\\/}/g" \
1189                                $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient/ogAdmClient.cfg > $INSTALL_TARGET/client/etc/ogAdmClient-$dev.cfg
1190                fi
1191                let i++
1192        done
1193        ln -f $INSTALL_TARGET/etc/ogAdmServer-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmServer.cfg
1194        ln -f $INSTALL_TARGET/etc/ogAdmRepo-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmRepo.cfg
1195        ln -f $INSTALL_TARGET/etc/ogAdmAgent-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmAgent.cfg
1196        ln -f $INSTALL_TARGET/client/etc/ogAdmClient-$DEFAULTDEV.cfg $INSTALL_TARGET/client/etc/ogAdmClient.cfg
1197        ln -f $INSTALL_TARGET/www/controlacceso-$DEFAULTDEV.php $INSTALL_TARGET/www/controlacceso.php
1198        chown root:root $INSTALL_TARGET/etc/{ogAdmServer,ogAdmAgent}*.cfg
1199        chmod 600 $INSTALL_TARGET/etc/{ogAdmServer,ogAdmAgent}*.cfg
1200        chown $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/controlacceso*.php
1201        chmod 600 $INSTALL_TARGET/www/controlacceso*.php
1202        echoAndLog "${FUNCNAME}(): Starting OpenGnSys services."
1203        $OGINIT start
1204}
1205
1206
1207#####################################################################
1208#######  Función de resumen informativo de la instalación
1209#####################################################################
1210
1211function installationSummary()
1212{
1213        # Crear fichero de versión y revisión, si no existe.
1214        local VERSIONFILE="$INSTALL_TARGET/doc/VERSION.txt"
1215        local REVISION=$(LANG=C svn info $SVN_URL|awk '/Rev:/ {print "r"$4}')
1216        [ -f $VERSIONFILE ] || echo "OpenGnSys" >$VERSIONFILE
1217        perl -pi -e "s/($| r[0-9]*)/ $REVISION/" $VERSIONFILE
1218
1219        # Mostrar información.
1220        echo
1221        echoAndLog "OpenGnSys Installation Summary"
1222        echo       "=============================="
1223        echoAndLog "Project version:                  $(cat $VERSIONFILE 2>/dev/null)"
1224        echoAndLog "Components installed:             $COMPONENTS"
1225        echoAndLog "Installation directory:           $INSTALL_TARGET"
1226        echoAndLog "Repository directory:             $INSTALL_TARGET/images"
1227        echoAndLog "DHCP configuration directory:     $DHCPCFGDIR"
1228        echoAndLog "TFTP configuration directory:     /var/lib/tftpboot"
1229        echoAndLog "Samba configuration directory:    /etc/samba"
1230        echoAndLog "Samba client username:            $SAMBAUSER"
1231        echoAndLog "Web Console URL:                  $OPENGNSYS_CONSOLEURL"
1232        echoAndLog "Web Console admin username:       $OPENGNSYS_DB_USER"
1233        echoAndLog "Web Console admin password:       $OPENGNSYS_DB_PASSWD"
1234        echo
1235        echoAndLog "Post-Installation Instructions:"
1236        echo       "==============================="
1237        echoAndLog "Review or edit all configuration files."
1238        echoAndLog "Insert DHCP configuration data and restart service."
1239        echoAndLog "Log-in as Web Console admin user."
1240        echoAndLog " - Review default Organization data and assign default user."
1241        echoAndLog "Log-in as Web Console organization user."
1242        echoAndLog " - Insert OpenGnSys data (rooms, computers, menus, etc)."
1243echo
1244}
1245
1246
1247
1248#####################################################################
1249####### Proceso de instalación de OpenGnSys
1250#####################################################################
1251
1252echoAndLog "OpenGnSys installation begins at $(date)"
1253pushd $WORKDIR
1254
1255# Detectar datos de auto-configuración del instalador.
1256autoConfigure
1257
1258# Detectar parámetros de red y comprobar si hay conexión.
1259getNetworkSettings
1260if [ $? -ne 0 ]; then
1261        errorAndLog "Error reading default network settings."
1262        exit 1
1263fi
1264checkNetworkConnection
1265if [ $? -ne 0 ]; then
1266        errorAndLog "Error connecting to server. Causes:"
1267        errorAndLog " - Network is unreachable, review devices parameters."
1268        errorAndLog " - You are inside a private network, configure the proxy service."
1269        errorAndLog " - Server is temporally down, try agian later."
1270        exit 1
1271fi
1272
1273# Detener servicios de OpenGnSys, si están activos previamente.
1274[ -f /etc/init.d/opengnsys ] && /etc/init.d/opengnsys stop
1275
1276# Actualizar repositorios
1277eval $UPDATEPKGLIST
1278
1279# Instalación de dependencias (paquetes de sistema operativo).
1280checkPackage "mysql-server"; MYSQLINSTALLED=$?
1281checkAndInstall
1282if [ $? -ne 0 ]; then
1283        echoAndLog "Error while installing some dependeces, please verify your server installation before continue"
1284        exit 1
1285fi
1286
1287# Arbol de directorios de OpenGnSys.
1288createDirs ${INSTALL_TARGET}
1289if [ $? -ne 0 ]; then
1290        errorAndLog "Error while creating directory paths!"
1291        exit 1
1292fi
1293
1294# Si es necesario, descarga el repositorio de código en directorio temporal
1295if [ $USESVN -eq 1 ]; then
1296        svnExportCode $SVN_URL
1297        if [ $? -ne 0 ]; then
1298                errorAndLog "Error while getting code from svn"
1299                exit 1
1300        fi
1301else
1302        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
1303fi
1304
1305# Compilar código fuente de los servicios de OpenGnSys.
1306servicesCompilation
1307if [ $? -ne 0 ]; then
1308        errorAndLog "Error while compiling OpenGnsys services"
1309        exit 1
1310fi
1311
1312# Copiar carpeta Interface entre administración y motor de clonación.
1313copyInterfaceAdm
1314if [ $? -ne 0 ]; then
1315        errorAndLog "Error while copying Administration Interface"
1316        exit 1
1317fi
1318
1319# Configurando tftp
1320tftpConfigure
1321
1322# Configuración ejemplo DHCP
1323dhcpConfigure
1324if [ $? -ne 0 ]; then
1325        errorAndLog "Error while copying your dhcp server files!"
1326        exit 1
1327fi
1328
1329# Copiar ficheros de servicios OpenGnSys Server.
1330copyServerFiles ${INSTALL_TARGET}
1331if [ $? -ne 0 ]; then
1332        errorAndLog "Error while copying the server files!"
1333        exit 1
1334fi
1335
1336# Instalar Base de datos de OpenGnSys Admin.
1337if [ $MYSQLINSTALLED -ne 0 ]; then
1338        mysqlSetRootPassword ${MYSQL_ROOT_PASSWORD}
1339else
1340        mysqlGetRootPassword
1341fi
1342
1343mysqlTestConnection ${MYSQL_ROOT_PASSWORD}
1344if [ $? -ne 0 ]; then
1345        errorAndLog "Error while connection to mysql"
1346        exit 1
1347fi
1348mysqlDbExists ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DATABASE}
1349if [ $? -ne 0 ]; then
1350        echoAndLog "Creating Web Console database"
1351        mysqlCreateDb ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DATABASE}
1352        if [ $? -ne 0 ]; then
1353                errorAndLog "Error while creating Web Console database"
1354                exit 1
1355        fi
1356else
1357        echoAndLog "Web Console database exists, ommiting creation"
1358fi
1359
1360mysqlCheckUserExists ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DB_USER}
1361if [ $? -ne 0 ]; then
1362        echoAndLog "Creating user in database"
1363        mysqlCreateAdminUserToDb ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DATABASE} ${OPENGNSYS_DB_USER} "${OPENGNSYS_DB_PASSWD}"
1364        if [ $? -ne 0 ]; then
1365                errorAndLog "Error while creating database user"
1366                exit 1
1367        fi
1368
1369fi
1370
1371mysqlCheckDbIsEmpty ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DATABASE}
1372if [ $? -eq 0 ]; then
1373        echoAndLog "Creating tables..."
1374        if [ -f $WORKDIR/$OPENGNSYS_DB_CREATION_FILE ]; then
1375                mysqlImportSqlFileToDb ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_CREATION_FILE
1376        else
1377                errorAndLog "Unable to locate $WORKDIR/$OPENGNSYS_DB_CREATION_FILE!!"
1378                exit 1
1379        fi
1380else
1381        # Si existe fichero ogBDAdmin-VersLocal-VersRepo.sql; aplicar cambios.
1382        INSTVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt)
1383        REPOVERSION=$(awk '{print $2}' $WORKDIR/opengnsys/doc/VERSION.txt)
1384        OPENGNSYS_DB_UPDATE_FILE="opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
1385        if [ -f $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE ]; then
1386                echoAndLog "Updating tables from version $INSTVERSION to $REPOVERSION"
1387                mysqlImportSqlFileToDb ${MYSQL_ROOT_PASSWORD} ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE
1388        else
1389                echoAndLog "Database unchanged."
1390        fi
1391fi
1392
1393# copiando paqinas web
1394installWebFiles
1395# Generar páqinas web de documentación de la API
1396makeDoxygenFiles
1397
1398# Creando configuración de Apache
1399openGnsysInstallWebConsoleApacheConf $INSTALL_TARGET $APACHECFGDIR
1400if [ $? -ne 0 ]; then
1401        errorAndLog "Error configuring Apache for OpenGnSys Admin"
1402        exit 1
1403fi
1404
1405popd
1406
1407
1408# Crear la estructura de los accesos al servidor desde el cliente (shared)
1409copyClientFiles
1410if [ $? -ne 0 ]; then
1411        errorAndLog "Error creating client structure"
1412fi
1413
1414# Crear la estructura del cliente de OpenGnSys
1415clientCreate
1416if [ $? -ne 0 ]; then
1417        errorAndLog "Error creating client"
1418        exit 1
1419fi
1420# Configuración Samba
1421smbConfigure
1422if [ $? -ne 0 ]; then
1423        errorAndLog "Error while configuring Samba server!"
1424        exit 1
1425fi
1426
1427# Configuración de servicios de OpenGnSys
1428openGnsysConfigure
1429
1430# Mostrar sumario de la instalación e instrucciones de post-instalación.
1431installationSummary
1432
1433#rm -rf $WORKDIR
1434echoAndLog "OpenGnSys installation finished at $(date)"
1435
Note: See TracBrowser for help on using the repository browser.