source: installer/opengnsys_installer.sh @ a37e5fc4

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

#804: Instalar y actualizar a PHP 7.

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

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