source: installer/opengnsys_installer.sh @ 208ee50

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 208ee50 was 3e7d77b, checked in by ramon <ramongomez@…>, 9 years ago

#736: Revertir movimiento de fichero de revisión r5011 y modificar instalador y actualizador para copiar el contenido del directorio server/lib al servidor.

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