source: installer/opengnsys_installer.sh @ 5aa8b28

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 5aa8b28 was f9e3393, checked in by ramon <ramongomez@…>, 11 years ago

#616: Instalador compatible con configuración de Apache 2.4 y de versiones anteriores.

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

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