source: installer/opengnsys_installer.sh @ 49275c7

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

Versión 1.0.5, #565: Crear credenciales para acceso Rsync iguales a las de Samba.

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

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