source: installer/opengnsys_installer_v1.0.2.sh @ 71b9d337

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 71b9d337 was 700299b, checked in by ramon <ramongomez@…>, 14 years ago

Versión 1.0.2: instalador configura logrotate desde la plantilla predefinida (cerrar #425)

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

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