source: installer/opengnsys_installer.sh @ d81fc6a

Last change on this file since d81fc6a was fac0b87, checked in by ramon <ramongomez@…>, 8 years ago

#754: Integrar los cambios de la versión de mantenimiento OpenGnSys 1.0.6b a la rama principal.

git-svn-id: https://opengnsys.es/svn/trunk@5143 a21b9725-9963-47de-94b9-378ad31fedc9

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