source: installer/opengnsys_installer.sh @ 1cf578b

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

Versión 1.0.4, #414: Desinstalador compatible con varias distribuciones.

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

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