source: installer/opengnsys_installer.sh @ cead9e3

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 cead9e3 was a482a77, checked in by ramon <ramongomez@…>, 10 years ago

#724: Instalador y actualizador descargan ogLive 1.1.0-rc1 basado en Ubuntu 15.04 con Kernel 3.19

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

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