source: installer/opengnsys_installer.sh @ b83843c

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

Versión 1.0.4, #414: Parar IPTables en la instalación en CentOS.

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

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