source: installer/opengnsys_installer.sh @ 9965062

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

#453: Instalar dependencias para autentificación con LDAP.

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

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