source: installer/opengnsys_installer_v1.0.2.sh @ 1616b6e

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

Versión 1.0.2: corregida errata en creación de enlaces simbólicos en instalador 1.0.2 (modifica #410)

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

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