source: installer/opengnsys_installer.sh @ 80fd30e

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 80fd30e was 103bc82, checked in by ramon <ramongomez@…>, 8 years ago

#718: Instalador y actualizador configuran tipo MIME para que descargar paquetes macOS como binarios.

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

  • Property mode set to 100755
File size: 56.4 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 moreutils jq )
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 moreutils jq )
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        local SWAGGERFILE="swagger-ui-2.2.5.zip"
1045
1046        echoAndLog "${FUNCNAME}(): Installing web files..."
1047        # Copiar ficheros.
1048        cp -a $WORKDIR/opengnsys/admin/WebConsole/* $INSTALL_TARGET/www   #*/ comentario para Doxygen.
1049        if [ $? != 0 ]; then
1050                errorAndLog "${FUNCNAME}(): Error copying web files."
1051                exit 1
1052        fi
1053        find $INSTALL_TARGET/www -name .svn -type d -exec rm -fr {} \; 2>/dev/null
1054
1055        # Descomprimir librerías: XAJAX, Slim y Swagger-UI.
1056        unzip -o $WORKDIR/opengnsys/admin/$XAJAXFILE -d $INSTALL_TARGET/www/xajax
1057        unzip -o $WORKDIR/opengnsys/admin/$SLIMFILE -d $INSTALL_TARGET/www/rest
1058        unzip -o $WORKDIR/opengnsys/admin/$SWAGGERFILE -d $INSTALL_TARGET/www/rest
1059
1060        # Compatibilidad con dispositivos móviles.
1061        COMPATDIR="$INSTALL_TARGET/www/principal"
1062        for f in acciones administracion aula aulas hardwares imagenes menus repositorios softwares; do
1063                sed 's/clickcontextualnodo/clicksupnodo/g' $COMPATDIR/$f.php > $COMPATDIR/$f.device.php
1064        done
1065        cp -a $COMPATDIR/imagenes.device.php $COMPATDIR/imagenes.device4.php
1066        # Cambiar permisos para ficheros especiales.
1067        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/images/{fotos,iconos}
1068        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/tmp/
1069        # Fichero de logs del agente OGAgent.
1070        touch $INSTALL_TARGET/log/ogagent.log
1071        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/log/ogagent.log
1072
1073        echoAndLog "${FUNCNAME}(): Web files installed successfully."
1074}
1075
1076# Configuración específica de Apache.
1077function installWebConsoleApacheConf()
1078{
1079        if [ $# -ne 2 ]; then
1080                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1081                exit 1
1082        fi
1083
1084        local path_opengnsys_base="$1"
1085        local path_apache2_confd="$2"
1086        local CONSOLEDIR=${path_opengnsys_base}/www
1087
1088        if [ ! -d $path_apache2_confd ]; then
1089                errorAndLog "${FUNCNAME}(): path to apache2 conf.d can not found, verify your server installation"
1090                return 1
1091        fi
1092
1093        mkdir -p $path_apache2_confd/{sites-available,sites-enabled}
1094
1095        echoAndLog "${FUNCNAME}(): creating apache2 config file.."
1096
1097        # Activar HTTPS.
1098        $APACHESSLMOD
1099        $APACHEENABLESSL
1100        $APACHEMAKECERT
1101        # Activar módulo Rewrite.
1102        $APACHEREWRITEMOD
1103        # Definir ficheros .pkg como binarios para descargar paquetes macOS.
1104        sed -i '/pkg/! s/octet-stream\(.*\)/octet-stream\1 pkg/' /etc/mime-types
1105        # Genera configuración de consola web a partir del fichero plantilla.
1106        if [ -n "$(apachectl -v | grep "2\.[0-2]")" ]; then
1107                # Configuración para versiones anteriores de Apache.
1108                sed -e "s/CONSOLEDIR/${CONSOLEDIR//\//\\/}/g" \
1109                        $WORKDIR/opengnsys/server/etc/apache-prev2.4.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}
1110        else
1111                # Configuración específica a partir de Apache 2.4
1112                sed -e "s/CONSOLEDIR/${CONSOLEDIR//\//\\/}/g" \
1113                        $WORKDIR/opengnsys/server/etc/apache.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf
1114        fi
1115        $APACHEENABLEOG
1116        if [ $? -ne 0 ]; then
1117                errorAndLog "${FUNCNAME}(): config file can't be linked to apache conf, verify your server installation"
1118                return 1
1119        fi
1120        echoAndLog "${FUNCNAME}(): config file created and linked, restarting apache daemon"
1121        service=$APACHESERV
1122        $ENABLESERVICE; $STARTSERVICE
1123        return 0
1124}
1125
1126
1127# Crear documentación Doxygen para la consola web.
1128function makeDoxygenFiles()
1129{
1130        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
1131        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
1132                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
1133        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
1134                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
1135                return 1
1136        fi
1137        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
1138        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/api
1139        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
1140}
1141
1142
1143# Crea la estructura base de la instalación de opengnsys
1144function createDirs()
1145{
1146        if [ $# -ne 1 ]; then
1147                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1148                exit 1
1149        fi
1150
1151        local path_opengnsys_base="$1"
1152
1153        # Crear estructura de directorios.
1154        echoAndLog "${FUNCNAME}(): creating directory paths in $path_opengnsys_base"
1155        mkdir -p $path_opengnsys_base
1156        mkdir -p $path_opengnsys_base/bin
1157        mkdir -p $path_opengnsys_base/client
1158        mkdir -p $path_opengnsys_base/doc
1159        mkdir -p $path_opengnsys_base/etc
1160        mkdir -p $path_opengnsys_base/lib
1161        mkdir -p $path_opengnsys_base/log/clients
1162        ln -fs $path_opengnsys_base/log /var/log/opengnsys
1163        mkdir -p $path_opengnsys_base/sbin
1164        mkdir -p $path_opengnsys_base/www
1165        mkdir -p $path_opengnsys_base/images
1166        mkdir -p $TFTPCFGDIR
1167        ln -fs $TFTPCFGDIR $path_opengnsys_base/tftpboot
1168        mkdir -p $path_opengnsys_base/tftpboot/menu.lst
1169        if [ $? -ne 0 ]; then
1170                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
1171                return 1
1172        fi
1173
1174        # Crear usuario ficticio.
1175        if id -u $OPENGNSYS_CLIENT_USER &>/dev/null; then
1176                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENT_USER\" is already created"
1177        else
1178                echoAndLog "${FUNCNAME}(): creating OpenGnsys user"
1179                useradd $OPENGNSYS_CLIENT_USER 2>/dev/null
1180                if [ $? -ne 0 ]; then
1181                        errorAndLog "${FUNCNAME}(): error creating OpenGnsys user"
1182                        return 1
1183                fi
1184        fi
1185
1186        # Establecer los permisos básicos.
1187        echoAndLog "${FUNCNAME}(): setting directory permissions"
1188        chmod -R 775 $path_opengnsys_base/{log/clients,images}
1189        chown -R :$OPENGNSYS_CLIENT_USER $path_opengnsys_base/{log/clients,images}
1190        if [ $? -ne 0 ]; then
1191                errorAndLog "${FUNCNAME}(): error while setting permissions"
1192                return 1
1193        fi
1194
1195        # Mover el fichero de registro de instalación al directorio de logs.
1196        echoAndLog "${FUNCNAME}(): moving installation log file"
1197        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
1198        chmod 600 $LOG_FILE
1199
1200        echoAndLog "${FUNCNAME}(): directory paths created"
1201        return 0
1202}
1203
1204# Copia ficheros de configuración y ejecutables genéricos del servidor.
1205function copyServerFiles ()
1206{
1207        if [ $# -ne 1 ]; then
1208                errorAndLog "${FUNCNAME}(): invalid number of parameters"
1209                exit 1
1210        fi
1211
1212        local path_opengnsys_base="$1"
1213
1214        # Lista de ficheros y directorios origen y de directorios destino.
1215        local SOURCES=( server/tftpboot \
1216                        server/bin \
1217                        repoman/bin \
1218                        server/lib \
1219                        admin/Sources/Services/ogAdmServerAux
1220                        admin/Sources/Services/ogAdmRepoAux
1221                        installer/opengnsys_uninstall.sh \
1222                        installer/opengnsys_update.sh \
1223                        installer/opengnsys_export.sh \
1224                        installer/opengnsys_import.sh \
1225                        doc )
1226        local TARGETS=( tftpboot \
1227                        bin \
1228                        bin \
1229                        lib \
1230                        sbin \
1231                        sbin \
1232                        lib \
1233                        lib \
1234                        lib \
1235                        lib \
1236                        doc )
1237
1238        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
1239                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
1240                exit 1
1241        fi
1242
1243        # Copiar ficheros.
1244        echoAndLog "${FUNCNAME}(): copying files to server directories"
1245
1246        pushd $WORKDIR/opengnsys
1247        local i
1248        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
1249                if [ -f "${SOURCES[$i]}" ]; then
1250                        echoAndLog "Copying ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1251                        cp -a "${SOURCES[$i]}" "${path_opengnsys_base}/${TARGETS[$i]}"
1252                elif [ -d "${SOURCES[$i]}" ]; then
1253                        echoAndLog "Copying content of ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1254                        cp -a "${SOURCES[$i]}"/* "${path_opengnsys_base}/${TARGETS[$i]}"
1255        else
1256                        warningAndLog "Unable to copy ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
1257                fi
1258        done
1259
1260        popd
1261}
1262
1263####################################################################
1264### Funciones de compilación de código fuente de servicios
1265####################################################################
1266
1267# Compilar los servicios de OpenGnsys
1268function servicesCompilation ()
1269{
1270        local hayErrores=0
1271
1272        # Compilar OpenGnsys Server
1273        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Server"
1274        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
1275        make && mv ogAdmServer $INSTALL_TARGET/sbin
1276        if [ $? -ne 0 ]; then
1277                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Server"
1278                hayErrores=1
1279        fi
1280        popd
1281        # Compilar OpenGnsys Repository Manager
1282        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Repository Manager"
1283        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo
1284        make && mv ogAdmRepo $INSTALL_TARGET/sbin
1285        if [ $? -ne 0 ]; then
1286                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Repository Manager"
1287                hayErrores=1
1288        fi
1289        popd
1290        # Compilar OpenGnsys Agent
1291        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Agent"
1292        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
1293        make && mv ogAdmAgent $INSTALL_TARGET/sbin
1294        if [ $? -ne 0 ]; then
1295                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Agent"
1296                hayErrores=1
1297        fi
1298        popd   
1299        # Compilar OpenGnsys Client
1300        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Client"
1301        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
1302        make && mv ogAdmClient ../../../../client/shared/bin
1303        if [ $? -ne 0 ]; then
1304                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Client"
1305                hayErrores=1
1306        fi
1307        popd
1308
1309        return $hayErrores
1310}
1311
1312####################################################################
1313### Funciones de copia de la Interface de administración
1314####################################################################
1315
1316# Copiar carpeta de Interface
1317function copyInterfaceAdm ()
1318{
1319        local hayErrores=0
1320       
1321        # Crear carpeta y copiar Interface
1322        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
1323        cp -ar $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client/interfaceAdm
1324        if [ $? -ne 0 ]; then
1325                echoAndLog "${FUNCNAME}(): error while copying Administration Interface Folder"
1326                hayErrores=1
1327        fi
1328        chown $OPENGNSYS_CLIENT_USER:$OPENGNSYS_CLIENT_USER $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
1329        chmod 700 $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
1330
1331        return $hayErrores
1332}
1333
1334####################################################################
1335### Funciones instalacion cliente opengnsys
1336####################################################################
1337
1338function copyClientFiles()
1339{
1340        local errstatus=0
1341
1342        echoAndLog "${FUNCNAME}(): Copying OpenGnsys Client files."
1343        cp -a $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
1344        if [ $? -ne 0 ]; then
1345                errorAndLog "${FUNCNAME}(): error while copying client estructure"
1346                errstatus=1
1347        fi
1348        find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null
1349       
1350        echoAndLog "${FUNCNAME}(): Copying OpenGnsys Cloning Engine files."
1351        mkdir -p $INSTALL_TARGET/client/lib/engine/bin
1352        cp -a $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
1353        if [ $? -ne 0 ]; then
1354                errorAndLog "${FUNCNAME}(): error while copying engine files"
1355                errstatus=1
1356        fi
1357       
1358        if [ $errstatus -eq 0 ]; then
1359                echoAndLog "${FUNCNAME}(): client copy files success."
1360        else
1361                errorAndLog "${FUNCNAME}(): client copy files with errors"
1362        fi
1363
1364        return $errstatus
1365}
1366
1367
1368# Crear cliente OpenGnsys.
1369function clientCreate()
1370{
1371        local DOWNLOADURL="http://$OPENGNSYS_SERVER/downloads"
1372        #local FILENAME=ogLive-wily-4.2.0-35-generic-r4919.iso          # 1.1.0-rc3
1373        local FILENAME=ogLive-xenial-4.4.0-34-generic-r4999.iso         # 1.1.0-rc4
1374        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
1375 
1376        # Descargar cliente, si es necesario.
1377        if [ -s $PROGRAMDIR/$FILENAME ]; then
1378                echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
1379                mv $PROGRAMDIR/$FILENAME $TARGETFILE
1380        else
1381                echoAndLog "${FUNCNAME}(): Downloading ogLive Client"
1382                $INSTALL_TARGET/bin/oglivecli download $FILENAME
1383        fi
1384        if [ ! -s $TARGETFILE ]; then
1385                errorAndLog "${FUNCNAME}(): Error loading OpenGnsys Client"
1386                return 1
1387        fi
1388
1389        # Montar imagen, copiar cliente ogclient y desmontar.
1390        echoAndLog "${FUNCNAME}(): Installing ogLive Client"
1391        echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | \
1392                        $INSTALL_TARGET/bin/oglivecli install $TARGETFILE
1393        # Adaptar permisos.
1394        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/tftpboot/menu.lst
1395
1396        echoAndLog "${FUNCNAME}(): Client generation success"
1397}
1398
1399
1400# Configuración básica de servicios de OpenGnsys
1401function openGnsysConfigure()
1402{
1403        local i=0
1404        local dev=""
1405        local CONSOLEURL
1406
1407        echoAndLog "${FUNCNAME}(): Copying init files."
1408        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
1409        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default /etc/default/opengnsys
1410        # Deshabilitar servicios de BitTorrent si no están instalados.
1411        if [ ! -e /usr/bin/bttrack ]; then
1412                sed -i 's/RUN_BTTRACKER="yes"/RUN_BTTRACKER="no"/; s/RUN_BTSEEDER="yes"/RUN_BTSEEDER="no"/' \
1413                        /etc/default/opengnsys
1414        fi
1415        echoAndLog "${FUNCNAME}(): Creating cron files."
1416        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
1417        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
1418        echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
1419        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
1420
1421        echoAndLog "${FUNCNAME}(): Creating logrotate configuration file."
1422        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1423                $WORKDIR/opengnsys/server/etc/logrotate.tmpl > /etc/logrotate.d/opengnsys
1424
1425        echoAndLog "${FUNCNAME}(): Creating OpenGnsys config files."
1426        for dev in ${DEVICE[*]}; do
1427                if [ -n "${SERVERIP[i]}" ]; then
1428                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1429                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1430                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1431                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1432                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer/ogAdmServer.cfg > $INSTALL_TARGET/etc/ogAdmServer-$dev.cfg
1433                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1434                            -e "s/REPOKEY/$OPENGNSYS_REPOKEY/g" \
1435                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo/ogAdmRepo.cfg > $INSTALL_TARGET/etc/ogAdmRepo-$dev.cfg
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                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent/ogAdmAgent.cfg > $INSTALL_TARGET/etc/ogAdmAgent-$dev.cfg
1441                        CONSOLEURL="https://${SERVERIP[i]}/opengnsys"
1442                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1443                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1444                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1445                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1446                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
1447                                $INSTALL_TARGET/www/controlacceso.php > $INSTALL_TARGET/www/controlacceso-$dev.php
1448                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1449                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
1450                                $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient/ogAdmClient.cfg > $INSTALL_TARGET/client/etc/ogAdmClient-$dev.cfg
1451                        if [ "$dev" == "$DEFAULTDEV" ]; then
1452                                OPENGNSYS_CONSOLEURL="$CONSOLEURL"
1453                        fi
1454                fi
1455                let i++
1456        done
1457        ln -f $INSTALL_TARGET/etc/ogAdmServer-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmServer.cfg
1458        ln -f $INSTALL_TARGET/etc/ogAdmRepo-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmRepo.cfg
1459        ln -f $INSTALL_TARGET/etc/ogAdmAgent-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmAgent.cfg
1460        ln -f $INSTALL_TARGET/client/etc/ogAdmClient-$DEFAULTDEV.cfg $INSTALL_TARGET/client/etc/ogAdmClient.cfg
1461        ln -f $INSTALL_TARGET/www/controlacceso-$DEFAULTDEV.php $INSTALL_TARGET/www/controlacceso.php
1462        chown root:root $INSTALL_TARGET/etc/{ogAdmServer,ogAdmAgent}*.cfg
1463        chmod 600 $INSTALL_TARGET/etc/{ogAdmServer,ogAdmAgent}*.cfg
1464        chown $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/controlacceso*.php
1465        chmod 600 $INSTALL_TARGET/www/controlacceso*.php
1466
1467        # Configuración del motor de clonación.
1468        # - Zona horaria del servidor.
1469        TZ=$(timedatectl status|awk -F"[:()]" '/Time.*zone/ {print $2}')
1470        cat << EOT >> $INSTALL_TARGET/client/etc/engine.cfg
1471# OpenGnsys Server timezone.
1472TZ="${TZ// /}"
1473EOT
1474
1475        # Revisar permisos generales.
1476        if [ -x $INSTALL_TARGET/bin/checkperms ]; then
1477                echoAndLog "${FUNCNAME}(): Checking permissions."
1478                OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENT_USER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" $INSTALL_TARGET/bin/checkperms
1479        fi
1480
1481        # Evitar inicio de duplicado en Ubuntu 14.04 (Upstart y SysV Init).
1482        if [ -f /etc/init/${MYSQLSERV}.conf ]; then
1483                service=$MYSQLSERV
1484                $DISABLESERVICE
1485        fi
1486
1487        echoAndLog "${FUNCNAME}(): Starting OpenGnsys services."
1488        service="opengnsys"
1489        $ENABLESERVICE; $STARTSERVICE
1490}
1491
1492
1493#####################################################################
1494#######  Función de resumen informativo de la instalación
1495#####################################################################
1496
1497function installationSummary()
1498{
1499        # Crear fichero de versión y revisión, si no existe.
1500        local VERSIONFILE="$INSTALL_TARGET/doc/VERSION.txt"
1501        [ -f $VERSIONFILE ] || echo "OpenGnsys Server" >$VERSIONFILE
1502        # Incluir datos de revisión, si se está instaladno desde el repositorio
1503        # de código o si no está incluida en el fichero de versión.
1504        if [ $USESVN -eq 1 ] || [ -z "$(awk '$3~/r[0-9]*/ {print}' $VERSIONFILE)" ]; then
1505                local REVISION=$(LANG=C svn info $SVN_URL|awk '/Rev:/ {print "r"$4}')
1506                perl -pi -e "s/($| r[0-9]*)/ $REVISION/" $VERSIONFILE
1507        fi
1508
1509        # Mostrar información.
1510        echo
1511        echoAndLog "OpenGnsys Installation Summary"
1512        echo       "=============================="
1513        echoAndLog "Project version:                  $(cat $VERSIONFILE 2>/dev/null)"
1514        echoAndLog "Installation directory:           $INSTALL_TARGET"
1515        echoAndLog "Installation log file:            $LOG_FILE"
1516        echoAndLog "Repository directory:             $INSTALL_TARGET/images"
1517        echoAndLog "DHCP configuration directory:     $DHCPCFGDIR"
1518        echoAndLog "TFTP configuration directory:     $TFTPCFGDIR"
1519        echoAndLog "Samba configuration directory:    $SAMBACFGDIR"
1520        echoAndLog "Web Console URL:                  $OPENGNSYS_CONSOLEURL"
1521        echoAndLog "Web Console access data:          specified in installer script"
1522        if grep -q "^RUN_BTTRACK.*no" /etc/default/opengnsys; then
1523                echoAndLog "BitTorrent service is disabled."
1524        fi
1525        echo
1526        echoAndLog "Post-Installation Instructions:"
1527        echo       "==============================="
1528        echoAndLog "Firewall service has been disabled and SELinux mode set to"
1529        echoAndLog "   permissive during OpenGnsys installation. Please check"
1530        echoAndLog "   ${FIREWALLSERV:-firewall} and SELinux configuration, if needed."
1531        echoAndLog "It's strongly recommended to synchronize this server with an NTP server."
1532        echoAndLog "Review or edit all configuration files."
1533        echoAndLog "Insert DHCP configuration data and restart service."
1534        echoAndLog "Optional: Log-in as Web Console admin user."
1535        echoAndLog " - Review default Organization data and assign access to users."
1536        echoAndLog "Log-in as Web Console organization user."
1537        echoAndLog " - Insert OpenGnsys data (labs, computers, menus, etc)."
1538echo
1539}
1540
1541
1542
1543#####################################################################
1544####### Proceso de instalación de OpenGnsys
1545#####################################################################
1546
1547echoAndLog "OpenGnsys installation begins at $(date)"
1548pushd $WORKDIR
1549
1550# Detectar datos iniciales de auto-configuración del instalador.
1551autoConfigure
1552
1553# Detectar parámetros de red y comprobar si hay conexión.
1554getNetworkSettings
1555if [ $? -ne 0 ]; then
1556        errorAndLog "Error reading default network settings."
1557        exit 1
1558fi
1559checkNetworkConnection
1560if [ $? -ne 0 ]; then
1561        errorAndLog "Error connecting to server. Causes:"
1562        errorAndLog " - Network is unreachable, review devices parameters."
1563        errorAndLog " - You are inside a private network, configure the proxy service."
1564        errorAndLog " - Server is temporally down, try agian later."
1565        exit 1
1566fi
1567
1568# Detener servicios de OpenGnsys, si están activos previamente.
1569[ -f /etc/init.d/opengnsys ] && /etc/init.d/opengnsys stop
1570
1571# Actualizar repositorios
1572updatePackageList
1573
1574# Instalación de dependencias (paquetes de sistema operativo).
1575declare -a notinstalled
1576checkDependencies DEPENDENCIES notinstalled
1577if [ $? -ne 0 ]; then
1578        installDependencies notinstalled
1579        if [ $? -ne 0 ]; then
1580                echoAndLog "Error while installing some dependeces, please verify your server installation before continue"
1581                exit 1
1582        fi
1583fi
1584if [ -n "$INSTALLEXTRADEPS" ]; then
1585        echoAndLog "Installing extra dependencies"
1586        for (( i=0; i<${#INSTALLEXTRADEPS[*]}; i++ )); do
1587                eval ${INSTALLEXTRADEPS[i]}
1588        done
1589fi     
1590
1591# Detectar datos de auto-configuración después de instalar paquetes.
1592autoConfigurePost
1593
1594# Arbol de directorios de OpenGnsys.
1595createDirs ${INSTALL_TARGET}
1596if [ $? -ne 0 ]; then
1597        errorAndLog "Error while creating directory paths!"
1598        exit 1
1599fi
1600
1601# Si es necesario, descarga el repositorio de código en directorio temporal
1602if [ $USESVN -eq 1 ]; then
1603        svnExportCode $SVN_URL
1604        if [ $? -ne 0 ]; then
1605                errorAndLog "Error while getting code from svn"
1606                exit 1
1607        fi
1608else
1609        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
1610fi
1611
1612# Compilar código fuente de los servicios de OpenGnsys.
1613servicesCompilation
1614if [ $? -ne 0 ]; then
1615        errorAndLog "Error while compiling OpenGnsys services"
1616        exit 1
1617fi
1618
1619# Copiar carpeta Interface entre administración y motor de clonación.
1620copyInterfaceAdm
1621if [ $? -ne 0 ]; then
1622        errorAndLog "Error while copying Administration Interface"
1623        exit 1
1624fi
1625
1626# Configuración de TFTP.
1627tftpConfigure
1628
1629# Configuración de Samba.
1630smbConfigure
1631if [ $? -ne 0 ]; then
1632        errorAndLog "Error while configuring Samba server!"
1633        exit 1
1634fi
1635
1636# Configuración de Rsync.
1637rsyncConfigure
1638
1639# Configuración ejemplo DHCP.
1640dhcpConfigure
1641if [ $? -ne 0 ]; then
1642        errorAndLog "Error while copying your dhcp server files!"
1643        exit 1
1644fi
1645
1646# Copiar ficheros de servicios OpenGnsys Server.
1647copyServerFiles ${INSTALL_TARGET}
1648if [ $? -ne 0 ]; then
1649        errorAndLog "Error while copying the server files!"
1650        exit 1
1651fi
1652
1653# Instalar base de datos de OpenGnsys Admin.
1654isInArray notinstalled "mysql-server" || isInArray notinstalled "mariadb-server"
1655if [ $? -eq 0 ]; then
1656        # Habilitar gestor de base de datos (MySQL, si falla, MariaDB).
1657        service=$MYSQLSERV
1658        $ENABLESERVICE
1659        if [ $? != 0 ]; then
1660                service=$MARIADBSERV
1661                $ENABLESERVICE
1662        fi
1663        # Activar gestor de base de datos.
1664        $STARTSERVICE
1665        # Asignar clave del usuario "root".
1666        mysqlSetRootPassword "${MYSQL_ROOT_PASSWORD}"
1667else
1668        # Si ya está instalado el gestor de bases de datos, obtener clave de "root",
1669        mysqlGetRootPassword
1670fi
1671
1672mysqlTestConnection "${MYSQL_ROOT_PASSWORD}"
1673if [ $? -ne 0 ]; then
1674        errorAndLog "Error while connection to mysql"
1675        exit 1
1676fi
1677mysqlDbExists ${OPENGNSYS_DATABASE}
1678if [ $? -ne 0 ]; then
1679        echoAndLog "Creating Web Console database"
1680        mysqlCreateDb ${OPENGNSYS_DATABASE}
1681        if [ $? -ne 0 ]; then
1682                errorAndLog "Error while creating Web Console database"
1683                exit 1
1684        fi
1685else
1686        echoAndLog "Web Console database exists, ommiting creation"
1687fi
1688
1689mysqlCheckUserExists ${OPENGNSYS_DB_USER}
1690if [ $? -ne 0 ]; then
1691        echoAndLog "Creating user in database"
1692        mysqlCreateAdminUserToDb ${OPENGNSYS_DATABASE} ${OPENGNSYS_DB_USER} "${OPENGNSYS_DB_PASSWD}"
1693        if [ $? -ne 0 ]; then
1694                errorAndLog "Error while creating database user"
1695                exit 1
1696        fi
1697
1698fi
1699
1700mysqlCheckDbIsEmpty ${OPENGNSYS_DATABASE}
1701if [ $? -eq 0 ]; then
1702        echoAndLog "Creating tables..."
1703        if [ -f $WORKDIR/$OPENGNSYS_DB_CREATION_FILE ]; then
1704                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_CREATION_FILE
1705        else
1706                errorAndLog "Unable to locate $WORKDIR/$OPENGNSYS_DB_CREATION_FILE!!"
1707                exit 1
1708        fi
1709else
1710        # Si existe fichero ogBDAdmin-VersLocal-VersRepo.sql; aplicar cambios.
1711        INSTVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt)
1712        REPOVERSION=$(awk '{print $2}' $WORKDIR/opengnsys/doc/VERSION.txt)
1713        OPENGNSYS_DB_UPDATE_FILE="opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
1714        if [ -f $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE ]; then
1715                echoAndLog "Updating tables from version $INSTVERSION to $REPOVERSION"
1716                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE
1717        else
1718                echoAndLog "Database unchanged."
1719        fi
1720fi
1721# Eliminar fichero temporal con credenciales de acceso a MySQL.
1722rm -f $TMPMYCNF
1723
1724# Copiando páqinas web.
1725installWebFiles
1726# Generar páqinas web de documentación de la API
1727makeDoxygenFiles
1728
1729# Creando configuración de Apache.
1730installWebConsoleApacheConf $INSTALL_TARGET $APACHECFGDIR
1731if [ $? -ne 0 ]; then
1732        errorAndLog "Error configuring Apache for OpenGnsys Admin"
1733        exit 1
1734fi
1735
1736popd
1737
1738# Crear la estructura de los accesos al servidor desde el cliente (shared)
1739copyClientFiles
1740if [ $? -ne 0 ]; then
1741        errorAndLog "Error creating client structure"
1742fi
1743
1744# Crear la estructura del cliente de OpenGnsys.
1745clientCreate
1746if [ $? -ne 0 ]; then
1747        errorAndLog "Error creating client"
1748        exit 1
1749fi
1750
1751# Configuración de servicios de OpenGnsys
1752openGnsysConfigure
1753
1754# Mostrar sumario de la instalación e instrucciones de post-instalación.
1755installationSummary
1756
1757#rm -rf $WORKDIR
1758echoAndLog "OpenGnsys installation finished at $(date)"
1759exit 0
1760
Note: See TracBrowser for help on using the repository browser.