source: installer/opengnsys_installer.sh @ 5fcf180

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 5fcf180 was 5fcf180, checked in by ramon <ramongomez@…>, 13 years ago

Versión 1.0.4, #414: Primeros pasos para instalación en CentOS 6.x de 64 bits.

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

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