source: installer/opengnsys_installer.sh @ b4a2555

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 b4a2555 was acfb07d, checked in by ramon <ramongomez@…>, 12 years ago

Versión 1.0.5, #562: Instalador guarda el registro de instalación en el directorio log de OpenGnSys.

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

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