source: installer/opengnsys_installer.sh @ f49cb88

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 f49cb88 was 6777e3e, checked in by ramon <ramongomez@…>, 9 years ago

#730 #755: Instalador y actualizador copian scripts de exportar e importar datos; actualizar lista de tickets cerrados.

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

  • Property mode set to 100755
File size: 56.2 KB
RevLine 
[a01156a]1#!/bin/bash
2
3#####################################################################
[5f21d34]4####### Script instalador OpenGnsys
5####### Autor: Luis Guillén <lguillen@unizar.es>
[a01156a]6#####################################################################
7
8
[9672640]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
[5f21d34]12DEFAULT_OPENGNSYS_DB_USER="usuog"               # Usuario por defecto de acceso a la base de datos
[9672640]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       
[4a3cd1f]15
[1e7eaab]16# Sólo ejecutable por usuario root
[6ef01d9]17if [ "$(whoami)" != 'root' ]; then
[1e7eaab]18        echo "ERROR: this program must run under root privileges!!"
19        exit 1
20fi
[9672640]21
[5f21d34]22echo -e "\\nOpenGnsys Installation"
[9672640]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
[5f21d34]41        echo -n -e "\\nEnter username for OpenGnsys console (${DEFAULT_OPENGNSYS_DB_USER}): "
[9672640]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
[5f21d34]55        echo -n -e "\\nEnter password for OpenGnsys console (${DEFAULT_OPENGNSYS_DB_PASSWD}): "
[9672640]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
[5f21d34]69        echo -n -e "\\nEnter root password for OpenGnsys client (${DEFAULT_OPENGNSYS_CLIENT_PASSWD}): "
[9672640]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=============================="
[1e7eaab]82
83# Comprobar si se ha descargado el paquete comprimido (USESVN=0) o sólo el instalador (USESVN=1).
[49c6891]84PROGRAMDIR=$(readlink -e $(dirname "$0"))
[35b0ef1]85PROGRAMNAME=$(basename "$0")
[07c3a59]86OPENGNSYS_SERVER="www.opengnsys.es"
[1e7eaab]87if [ -d "$PROGRAMDIR/../installer" ]; then
[6ef01d9]88        USESVN=0
[1e7eaab]89else
[6ef01d9]90        USESVN=1
[1e7eaab]91fi
[1a2fa9d8]92SVN_URL="http://$OPENGNSYS_SERVER/svn/branches/version1.1/"
[1e7eaab]93
[a01156a]94WORKDIR=/tmp/opengnsys_installer
[1e7eaab]95mkdir -p $WORKDIR
96
[5f21d34]97# Directorio destino de OpenGnsys.
[1e7eaab]98INSTALL_TARGET=/opt/opengnsys
[42a0e41]99
100# Registro de incidencias.
101OGLOGFILE=$INSTALL_TARGET/log/${PROGRAMNAME%.sh}.log
[acfb07d]102LOG_FILE=/tmp/$(basename $OGLOGFILE)
[a01156a]103
[fd021b0]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
[3aaf91d]110
[a01156a]111
112#####################################################################
[d168a46]113####### Funciones de configuración
114#####################################################################
115
116# Generar variables de configuración del instalador
117# Variables globales:
[5cc52295]118# - OSDISTRIB, OSVERSION - tipo y versión de la distribución GNU/Linux
[d168a46]119# - DEPENDENCIES - array de dependencias que deben estar instaladas
120# - UPDATEPKGLIST, INSTALLPKGS, CHECKPKGS - comandos para gestión de paquetes
[109e8b2]121# - INSTALLEXTRADEPS - instalar dependencias no incluidas en la distribución
[53fba30]122# - STARTSERVICE, ENABLESERVICE - iniciar y habilitar un servicio
[109e8b2]123# - STOPSERVICE, DISABLESERVICE - parar y deshabilitar un servicio
[53fba30]124# - APACHESERV, APACHECFGDIR, APACHESITESDIR, APACHEUSER, APACHEGROUP - servicio y configuración de Apache
[7825e9e]125# - APACHESSLMOD, APACHEENABLESSL, APACHEMAKECERT - habilitar módulo Apache y certificado SSL
[5f21d34]126# - APACHEENABLEOG, APACHEOGSITE, - habilitar sitio web de OpenGnsys
[53fba30]127# - INETDSERV - servicio Inetd
[09ac3b8]128# - FIREWALLSERV - servicio de cortabuegos IPTables/FirewallD
[53fba30]129# - DHCPSERV, DHCPCFGDIR - servicio y configuración de DHCP
[0f8100d]130# - MYSQLSERV, TMPMYCNF - servicio MySQL y fichero temporal con credenciales de acceso
131# - MARIADBSERV - servicio MariaDB (sustituto de MySQL en algunas distribuciones)
[e70925a]132# - RSYNCSERV, RSYNCCFGDIR - servicio y configuración de Rsync
[53fba30]133# - SAMBASERV, SAMBACFGDIR - servicio y configuración de Samba
[297df16]134# - TFTPSERV, TFTPCFGDIR, SYSLINUXDIR - servicio y configuración de TFTP/PXE
[d168a46]135function autoConfigure()
136{
[44f6582]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
[eb7b39d]140        OSDISTRIB="$ID"
[5cc52295]141        OSVERSION="$VERSION_ID"
[44f6582]142else
143        OSDISTRIB=$(lsb_release -is 2>/dev/null)
[5cc52295]144        OSVERSION=$(lsb_release -rs 2>/dev/null)
[44f6582]145fi
[5cc52295]146# Convertir distribución a minúsculas y obtener solo el 1er número de versión.
[eb7b39d]147OSDISTRIB="${OSDISTRIB,,}"
[5cc52295]148OSVERSION="${OSVERSION%%.*}"
[d168a46]149
[eb7b39d]150# Configuración según la distribución GNU/Linux (usar minúsculas).
[d168a46]151case "$OSDISTRIB" in
[eb7b39d]152        ubuntu|debian|linuxmint)
[a44e252]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 )
[d168a46]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"
[53fba30]157                if which service &>/dev/null; then
[7ba85a4]158                        STARTSERVICE="eval service \$service restart"
[109e8b2]159                        STOPSERVICE="eval service \$service stop"
[53fba30]160                else
[7ba85a4]161                        STARTSERVICE="eval /etc/init.d/\$service restart"
[109e8b2]162                        STOPSERVICE="eval /etc/init.d/\$service stop"
[53fba30]163                fi
[7ba85a4]164                ENABLESERVICE="eval update-rc.d \$service defaults"
[109e8b2]165                DISABLESERVICE="eval update-rc.d \$service disable"
[53fba30]166                APACHESERV=apache2
[d168a46]167                APACHECFGDIR=/etc/apache2
[643ca8c]168                APACHESITESDIR=sites-available
[53fba30]169                APACHEOGSITE=opengnsys
[d168a46]170                APACHEUSER="www-data"
171                APACHEGROUP="www-data"
[7ba85a4]172                APACHESSLMOD="a2enmod ssl"
[7829e4e]173                APACHEREWRITEMOD="a2enmod rewrite"
[7ba85a4]174                APACHEENABLESSL="a2ensite default-ssl"
[53fba30]175                APACHEENABLEOG="a2ensite $APACHEOGSITE"
[643ca8c]176                APACHEMAKECERT="make-ssl-cert generate-default-snakeoil --force-overwrite"
[53fba30]177                DHCPSERV=isc-dhcp-server
[83518d5]178                DHCPCFGDIR=/etc/dhcp
[f243a47]179                INETDSERV=xinetd
180                INETDCFGDIR=/etc/xinetd.d
[53fba30]181                MYSQLSERV=mysql
[0f8100d]182                MARIADBSERV=mariadb
[e70925a]183                RSYNCSERV=rsync
184                RSYNCCFGDIR=/etc
[53fba30]185                SAMBASERV=smbd
[d168a46]186                SAMBACFGDIR=/etc/samba
[297df16]187                SYSLINUXDIR=/usr/lib/syslinux
[d168a46]188                TFTPCFGDIR=/var/lib/tftpboot
189                ;;
[eb7b39d]190        fedora|centos)
[a44e252]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 )
[109e8b2]192                INSTALLEXTRADEPS=( 'rpm -Uv ftp://ftp.altlinux.org/pub/distributions/ALTLinux/5.1/branch/files/i586/RPMS/netpipes-4.2-alt1.i586.rpm'
[b8969db]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' )
[eb7b39d]194                if [ "$OSDISTRIB" == "centos" ]; then
[03cfd6e]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
[d168a46]197                INSTALLPKG="yum install -y"
[c79a2b3]198                CHECKPKG="rpm -q --quiet \$package"
[03cfd6e]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
[53fba30]211                APACHESERV=httpd
[d168a46]212                APACHECFGDIR=/etc/httpd/conf.d
[53fba30]213                APACHEOGSITE=opengnsys.conf
[d168a46]214                APACHEUSER="apache"
215                APACHEGROUP="apache"
[5f21d34]216                APACHEREWRITEMOD="sed -i '/rewrite/s/^#//' $APACHECFGDIR/../*.conf"
[53fba30]217                DHCPSERV=dhcpd
[d168a46]218                DHCPCFGDIR=/etc/dhcp
[09ac3b8]219                if firewall-cmd --state &>/dev/null; then
220                        FIREWALLSERV=firewalld
221                else
222                        FIREWALLSERV=iptables
223                fi
[53fba30]224                INETDSERV=xinetd
[f243a47]225                INETDCFGDIR=/etc/xinetd.d
[53fba30]226                MYSQLSERV=mysqld
[0f8100d]227                MARIADBSERV=mariadb
[e70925a]228                RSYNCSERV=rsync
229                RSYNCCFGDIR=/etc
[53fba30]230                SAMBASERV=smb
[d168a46]231                SAMBACFGDIR=/etc/samba
[297df16]232                SYSLINUXDIR=/usr/share/syslinux
[53fba30]233                TFTPSERV=tftp
[d168a46]234                TFTPCFGDIR=/var/lib/tftpboot
235                ;;
236        "")     echo "ERROR: Unknown Linux distribution, please install \"lsb_release\" command."
237                exit 1 ;;
[5f21d34]238        *)      echo "ERROR: Distribution not supported by OpenGnsys."
[d168a46]239                exit 1 ;;
240esac
[09bf701]241
242# Fichero de credenciales de acceso a MySQL.
243TMPMYCNF=/tmp/.my.cnf.$$
[d168a46]244}
245
[09ac3b8]246
[ff6c349]247# Modificar variables de configuración tras instalar paquetes del sistema.
248function autoConfigurePost()
249{
[09ac3b8]250local f
251
[44f6582]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
[09ac3b8]256# Configuraciones específicas para SELinux permisivo en distintas versiones.
[44f6582]257[ -f /selinux/enforce ] && echo 0 > /selinux/enforce
[e5f9c147]258for f in /etc/sysconfig/selinux /etc/selinux/config; do
[4fdf2b1]259        [ -f $f ] && perl -pi -e 's/SELINUX=enforcing/SELINUX=permissive/g' $f
[09ac3b8]260done
261selinuxenabled 2>/dev/null && setenforce 0 2>/dev/null
[ff6c349]262}
263
264
[83518d5]265# Cargar lista de paquetes del sistema y actualizar algunas variables de configuración
266# dependiendo de la versión instalada.
267function updatePackageList()
268{
[ad69c61]269local DHCPVERSION PHP5VERSION
[83518d5]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
[eb7b39d]276        ubuntu|linuxmint)       # Postconfiguación personalizada para Ubuntu.
[83518d5]277                # Configuración para DHCP v3.
[e4b1572]278                DHCPVERSION=$(apt-cache show $(apt-cache pkgnames|egrep "dhcp.?-server$") | \
[83518d5]279                              awk '/Version/ {print substr($2,1,1);}' | \
280                              sort -n | tail -1)
281                if [ $DHCPVERSION = 3 ]; then
[e4b1572]282                        DEPENDENCIES=( ${DEPENDENCIES[@]/isc-dhcp-server/dhcp3-server} )
[53fba30]283                        DHCPSERV=dhcp3-server
[83518d5]284                        DHCPCFGDIR=/etc/dhcp3
285                fi
[ad69c61]286                # Configuración para PHP 5 en Ubuntu 16.x+.
287                if [ -z "$(apt-cache pkgnames php5)" ]; then
[668f7dc]288                        eval $INSTALLPKG software-properties-common
[21f78d1]289                        add-apt-repository -y ppa:ondrej/php
[668f7dc]290                        eval $UPDATEPKGLIST
[ad69c61]291                fi
[21f78d1]292                PHP5VERSION=$(apt-cache pkgnames php5 | sort | head -1)
293                DEPENDENCIES=( ${DEPENDENCIES[@]//php5/$PHP5VERSION} )
[ad69c61]294                # Dependencias correctas para libmysqlclient.
[21f78d1]295                [ -z "$(apt-cache pkgnames libmysqlclient15)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//libmysqlclient15/libmysqlclient} )
[83518d5]296                ;;
[eb7b39d]297        centos) # Postconfiguación personalizada para CentOS.
[c525453]298                # Incluir repositorio de paquetes EPEL y paquetes específicos.
299                DEPENDENCIES=( ${DEPENDENCIES[@]} epel-release procps )
[2c8b9ed]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
[c525453]307                ;;
[eb7b39d]308        fedora) # Postconfiguación personalizada para Fedora.
[c525453]309                # Incluir paquetes específicos.
310                DEPENDENCIES=( ${DEPENDENCIES[@]} libstdc++-static.i686 btrfs-progs procps-ng )
[5cc52295]311                # Sustituir MySQL por MariaDB a partir de Fedora 20.
312                [ $OSVERSION -ge 20 ] && DEPENDENCIES=( ${DEPENDENCIES[*]/mysql-/mariadb-} )
[c79a2b3]313                ;;
[83518d5]314esac
315}
316
[d168a46]317
318#####################################################################
[a01156a]319####### Algunas funciones útiles de propósito general:
320#####################################################################
[d168a46]321
[13a01a7]322function getDateTime()
[a01156a]323{
[d168a46]324        date "+%Y%m%d-%H%M%S"
[a01156a]325}
326
327# Escribe a fichero y muestra por pantalla
[13a01a7]328function echoAndLog()
[a01156a]329{
[d168a46]330        local DATETIME=`getDateTime`
[87c7b02]331        echo "$1"
[d168a46]332        echo "$DATETIME;$SSH_CLIENT;$1" >> $LOG_FILE
[a01156a]333}
334
[87c7b02]335# Escribe a fichero y muestra mensaje de error
[13a01a7]336function errorAndLog()
[a01156a]337{
[d168a46]338        local DATETIME=`getDateTime`
[87c7b02]339        echo "ERROR: $1"
[d168a46]340        echo "$DATETIME;$SSH_CLIENT;ERROR: $1" >> $LOG_FILE
[a01156a]341}
342
[346eaee]343# Escribe a fichero y muestra mensaje de aviso
344function warningAndLog()
345{
346        local DATETIME=`getDateTime`
[cd86637]347        echo "Warning: $1"
[346eaee]348        echo "$DATETIME;$SSH_CLIENT;Warning: $1" >> $LOG_FILE
349}
350
[87c7b02]351# Comprueba si el elemento pasado en $2 está en el array $1
[13a01a7]352function isInArray()
[a01156a]353{
354        if [ $# -ne 2 ]; then
[13a01a7]355                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]356                exit 1
357        fi
358
359        local deps
[87c7b02]360        local is_in_array=1
361        local element="$2"
362
363        echoAndLog "${FUNCNAME}(): checking if $2 is in $1"
[5c33840]364        eval "deps=( \"\${$1[@]}\" )"
[a01156a]365
[87c7b02]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"
[a01156a]370                        is_in_array=0
371                fi
372        done
373
374        if [ $is_in_array -ne 0 ]; then
[87c7b02]375                echoAndLog "${FUNCNAME}(): $element NOT found in array"
[a01156a]376        fi
377
378        return $is_in_array
379}
380
[87c7b02]381
[a01156a]382#####################################################################
383####### Funciones de manejo de paquetes Debian
384#####################################################################
385
[13a01a7]386function checkPackage()
[a01156a]387{
388        package=$1
389        if [ -z $package ]; then
[73cfa0a]390                errorAndLog "${FUNCNAME}(): parameter required"
[a01156a]391                exit 1
392        fi
[73cfa0a]393        echoAndLog "${FUNCNAME}(): checking if package $package exists"
[d168a46]394        eval $CHECKPKG
[a01156a]395        if [ $? -eq 0 ]; then
[73cfa0a]396                echoAndLog "${FUNCNAME}(): package $package exists"
[a01156a]397                return 0
398        else
[73cfa0a]399                echoAndLog "${FUNCNAME}(): package $package doesn't exists"
[a01156a]400                return 1
401        fi
402}
403
[87c7b02]404# Recibe array con dependencias
[a01156a]405# por referencia deja un array con las dependencias no resueltas
406# devuelve 1 si hay alguna dependencia no resuelta
[13a01a7]407function checkDependencies()
[a01156a]408{
409        if [ $# -ne 2 ]; then
[73cfa0a]410                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]411                exit 1
412        fi
413
[73cfa0a]414        echoAndLog "${FUNCNAME}(): checking dependences"
[a01156a]415        uncompletedeps=0
416
417        # copia local del array del parametro 1
418        local deps
[5c33840]419        eval "deps=( \"\${$1[@]}\" )"
[a01156a]420
421        declare -a local_notinstalled
[5c33840]422
[a01156a]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
[73cfa0a]439        echoAndLog "${FUNCNAME}(): dependencies uncompleted: $uncompletedeps"
[a01156a]440        return $uncompletedeps
441}
442
443# Recibe un array con las dependencias y lo instala
[13a01a7]444function installDependencies()
[a01156a]445{
446        if [ $# -ne 1 ]; then
[813f617]447                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]448                exit 1
449        fi
[813f617]450        echoAndLog "${FUNCNAME}(): installing uncompleted dependencies"
[a01156a]451
452        # copia local del array del parametro 1
453        local deps
[5c33840]454        eval "deps=( \"\${$1[@]}\" )"
[a01156a]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
[813f617]463                errorAndLog "${FUNCNAME}(): array of dependeces is empty"
[a01156a]464                exit 1
465        fi
466
[c79a2b3]467        OLD_DEBIAN_FRONTEND=$DEBIAN_FRONTEND            # Debian/Ubuntu
[a01156a]468        export DEBIAN_FRONTEND=noninteractive
469
[d168a46]470        echoAndLog "${FUNCNAME}(): now $string_deps will be installed"
471        eval $INSTALLPKG $string_deps
[a01156a]472        if [ $? -ne 0 ]; then
[813f617]473                errorAndLog "${FUNCNAME}(): error installing dependencies"
[a01156a]474                return 1
475        fi
476
[c79a2b3]477        DEBIAN_FRONTEND=$OLD_DEBIAN_FRONTEND            # Debian/Ubuntu
[8244351]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
[c79a2b3]479
[813f617]480        echoAndLog "${FUNCNAME}(): dependencies installed"
[a01156a]481}
482
[13a01a7]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
[d168a46]492        local file="$1"
493        local dateymd=`date +%Y%m%d`
[13a01a7]494
[d168a46]495        if [ ! -f "$file" ]; then
[346eaee]496                warningAndLog "${FUNCNAME}(): file $file doesn't exists"
[13a01a7]497                return 1
498        fi
499
[d168a46]500        echoAndLog "${FUNCNAME}(): making $file backup"
[13a01a7]501
502        # realiza una copia de la última configuración como last
[d168a46]503        cp -a "$file" "${file}-LAST"
[13a01a7]504
505        # si para el día no hay backup lo hace, sino no
[d168a46]506        if [ ! -f "${file}-${dateymd}" ]; then
507                cp -a "$file" "${file}-${dateymd}"
[13a01a7]508        fi
509
[d168a46]510        echoAndLog "${FUNCNAME}(): $file backup success"
[13a01a7]511}
512
[a01156a]513#####################################################################
514####### Funciones para el manejo de bases de datos
515#####################################################################
516
517# This function set password to root
[13a01a7]518function mysqlSetRootPassword()
[a01156a]519{
520        if [ $# -ne 1 ]; then
[813f617]521                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]522                exit 1
523        fi
524
[e0edc14]525        local root_mysql="$1"
[813f617]526        echoAndLog "${FUNCNAME}(): setting root password in MySQL server"
[e0edc14]527        mysqladmin -u root password "$root_mysql"
[a01156a]528        if [ $? -ne 0 ]; then
[813f617]529                errorAndLog "${FUNCNAME}(): error while setting root password in MySQL server"
[a01156a]530                return 1
531        fi
[813f617]532        echoAndLog "${FUNCNAME}(): root password saved!"
[a01156a]533        return 0
534}
535
[892606b9]536# Si el servicio mysql esta ya instalado cambia la variable de la clave del root por la ya existente
[e0edc14]537function mysqlGetRootPassword()
538{
[892606b9]539        local pass_mysql
540        local pass_mysql2
[7c54b49]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
[e0edc14]546                echo "There is a MySQL service already installed."
547                read -p "Enter MySQL root password: " pass_mysql
[7c54b49]548                echo ""
[e0edc14]549                read -p "Confrim password:" pass_mysql2
[7c54b49]550                echo ""
551                stty echo
552                if [ "$pass_mysql" == "$pass_mysql2" ] ;then
[e0edc14]553                        MYSQL_ROOT_PASSWORD="$pass_mysql"
[7c54b49]554                        return 0
555                else
[e0edc14]556                        echo "The keys don't match. Do not configure the server's key,"
557                        echo "transactions in the database will give error."
[7c54b49]558                        return 1
559                fi
[892606b9]560        fi
561}
562
[a01156a]563# comprueba si puede conectar con mysql con el usuario root
564function mysqlTestConnection()
565{
566        if [ $# -ne 1 ]; then
[e0edc14]567                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]568                exit 1
569        fi
570
[09bf701]571        local root_password="$1"
[e0edc14]572        echoAndLog "${FUNCNAME}(): checking connection to mysql..."
[09bf701]573        # Componer fichero con credenciales de conexión a MySQL.
574        touch $TMPMYCNF
575        chmod 600 $TMPMYCNF
576        cat << EOT > $TMPMYCNF
[c073224]577[client]
[09bf701]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
[a01156a]585        if [ $? -ne 0 ]; then
[e0edc14]586                errorAndLog "${FUNCNAME}(): connection to mysql failed, check root password and if daemon is running!"
[a01156a]587                return 1
588        else
[e0edc14]589                echoAndLog "${FUNCNAME}(): connection success"
[a01156a]590                return 0
591        fi
592}
593
594# comprueba si la base de datos existe
595function mysqlDbExists()
596{
[09bf701]597        if [ $# -ne 1 ]; then
[e0edc14]598                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]599                exit 1
600        fi
601
[09bf701]602        local database="$1"
[e0edc14]603        echoAndLog "${FUNCNAME}(): checking if $database exists..."
[09bf701]604        echo "show databases" | mysql --defaults-extra-file=$TMPMYCNF | grep "^${database}$"
[a01156a]605        if [ $? -ne 0 ]; then
[e0edc14]606                echoAndLog "${FUNCNAME}():database $database doesn't exists"
[a01156a]607                return 1
608        else
[e0edc14]609                echoAndLog "${FUNCNAME}():database $database exists"
[a01156a]610                return 0
611        fi
612}
613
[0a735488]614# Comprueba si la base de datos está vacía.
[a01156a]615function mysqlCheckDbIsEmpty()
616{
[09bf701]617        if [ $# -ne 1 ]; then
[e0edc14]618                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]619                exit 1
620        fi
621
[09bf701]622        local database="$1"
[e0edc14]623        echoAndLog "${FUNCNAME}(): checking if $database is empty..."
[09bf701]624        num_tablas=`echo "show tables" | mysql --defaults-extra-file=$TMPMYCNF "${database}" | wc -l`
[a01156a]625        if [ $? -ne 0 ]; then
[e0edc14]626                errorAndLog "${FUNCNAME}(): error executing query, check database and root password"
[a01156a]627                exit 1
628        fi
629
630        if [ $num_tablas -eq 0 ]; then
[e0edc14]631                echoAndLog "${FUNCNAME}():database $database is empty"
[a01156a]632                return 0
633        else
[e0edc14]634                echoAndLog "${FUNCNAME}():database $database has tables"
[a01156a]635                return 1
636        fi
637
638}
639
[0a735488]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.
[a01156a]648function mysqlImportSqlFileToDb()
649{
[09bf701]650        if [ $# -ne 2 ]; then
[c5ce04c]651                errorAndLog "${FNCNAME}(): invalid number of parameters"
[a01156a]652                exit 1
653        fi
654
[09bf701]655        local database="$1"
656        local sqlfile="$2"
[c4321ae]657        local tmpfile=$(mktemp)
[d168a46]658        local i=0
659        local dev=""
[c4321ae]660        local status
[8e0f770]661        # Claves aleatorias para acceso a las APIs REST.
[7829e4e]662        local OPENGNSYS_APIKEY=$(php -r 'echo md5(uniqid(rand(), true));')
[f9b5714]663        OPENGNSYS_REPOKEY=$(php -r 'echo md5(uniqid(rand(), true));')
[a01156a]664
665        if [ ! -f $sqlfile ]; then
[c5ce04c]666                errorAndLog "${FUNCNAME}(): Unable to locate $sqlfile!!"
[a01156a]667                return 1
668        fi
669
[d168a46]670        echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..."
[c4321ae]671        chmod 600 $tmpfile
[d168a46]672        for dev in ${DEVICE[*]}; do
[73a1bd6]673                if [ "${DEVICE[i]}" == "$DEFAULTDEV" ]; then
[d168a46]674                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
675                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
676                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
[7829e4e]677                            -e "s/APIKEY/$OPENGNSYS_APIKEY/g" \
[8e0f770]678                            -e "s/REPOKEY/$OPENGNSYS_REPOKEY/g" \
[d168a46]679                                $sqlfile > $tmpfile
680                fi
681                let i++
682        done
[09bf701]683        mysql --defaults-extra-file=$TMPMYCNF --default-character-set=utf8 "${database}" < $tmpfile
[c4321ae]684        status=$?
685        rm -f $tmpfile
686        if [ $status -ne 0 ]; then
[c5ce04c]687                errorAndLog "${FUNCNAME}(): error while importing $sqlfile in database $database"
[a01156a]688                return 1
689        fi
[c5ce04c]690        echoAndLog "${FUNCNAME}(): file imported to database $database"
[a01156a]691        return 0
692}
693
694# Crea la base de datos
695function mysqlCreateDb()
696{
[09bf701]697        if [ $# -ne 1 ]; then
[a555f49]698                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]699                exit 1
700        fi
701
[09bf701]702        local database="$1"
[a01156a]703
[a555f49]704        echoAndLog "${FUNCNAME}(): creating database..."
[09bf701]705        mysqladmin --defaults-extra-file=$TMPMYCNF create $database
[a01156a]706        if [ $? -ne 0 ]; then
[a555f49]707                errorAndLog "${FUNCNAME}(): error while creating database $database"
[a01156a]708                return 1
709        fi
[a555f49]710        echoAndLog "${FUNCNAME}(): database $database created"
[a01156a]711        return 0
712}
713
[0a735488]714# Comprueba si ya está definido el usuario de acceso a la BD.
[a01156a]715function mysqlCheckUserExists()
716{
[09bf701]717        if [ $# -ne 1 ]; then
[e0edc14]718                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]719                exit 1
720        fi
721
[09bf701]722        local userdb="$1"
[a01156a]723
[e0edc14]724        echoAndLog "${FUNCNAME}(): checking if $userdb exists..."
[09bf701]725        echo "select user from user where user='${userdb}'\\G" |mysql --defaults-extra-file=$TMPMYCNF mysql | grep user
[a01156a]726        if [ $? -ne 0 ]; then
[e0edc14]727                echoAndLog "${FUNCNAME}(): user doesn't exists"
[a01156a]728                return 1
729        else
[e0edc14]730                echoAndLog "${FUNCNAME}(): user already exists"
[a01156a]731                return 0
732        fi
733
734}
735
736# Crea un usuario administrativo para la base de datos
737function mysqlCreateAdminUserToDb()
738{
[09bf701]739        if [ $# -ne 3 ]; then
[e0edc14]740                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]741                exit 1
742        fi
743
[09bf701]744        local database="$1"
745        local userdb="$2"
746        local passdb="$3"
[a01156a]747
[e0edc14]748        echoAndLog "${FUNCNAME}(): creating admin user ${userdb} to database ${database}"
[a01156a]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
[09bf701]755        mysql --defaults-extra-file=$TMPMYCNF < $WORKDIR/create_${database}.sql
[a01156a]756        if [ $? -ne 0 ]; then
[e0edc14]757                errorAndLog "${FUNCNAME}(): error while creating user in mysql"
[a01156a]758                rm -f $WORKDIR/create_${database}.sql
759                return 1
760        else
[e0edc14]761                echoAndLog "${FUNCNAME}(): user created ok"
[a01156a]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
[0a735488]772# Obtiene el código fuente del proyecto desde el servidor SVN.
[13a01a7]773function svnExportCode()
774{
775        if [ $# -ne 1 ]; then
776                errorAndLog "${FUNCNAME}(): invalid number of parameters"
777                exit 1
778        fi
779
[6090a2d]780        local url="$1"
[13a01a7]781
782        echoAndLog "${FUNCNAME}(): downloading subversion code..."
783
[6090a2d]784        svn export --force "$url" opengnsys
[13a01a7]785        if [ $? -ne 0 ]; then
[5f21d34]786                errorAndLog "${FUNCNAME}(): error getting OpenGnsys code from $url"
[13a01a7]787                return 1
788        fi
789        echoAndLog "${FUNCNAME}(): subversion code downloaded"
790        return 0
791}
792
793
[892606b9]794############################################################
[7586ca3]795###  Detectar red
796############################################################
797
[07c3a59]798# Comprobar si existe conexión.
799function checkNetworkConnection()
800{
[09ac3b8]801        echoAndLog "${FUNCNAME}(): Disabling Firewall: $FIREWALLSERV."
802        if [ -n "$FIREWALLSERV" ]; then
803                service=$FIREWALLSERV
[b83843c]804                $STOPSERVICE; $DISABLESERVICE
805        fi
[109e8b2]806
[5f21d34]807        echoAndLog "${FUNCNAME}(): Checking OpenGnsys server conectivity."
[07c3a59]808        OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"www.opengnsys.es"}
[225e859]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
[07c3a59]817}
818
819# Obtener los parámetros de red de la interfaz por defecto.
[7586ca3]820function getNetworkSettings()
821{
[d168a46]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
[109e8b2]836        echoAndLog "${FUNCNAME}(): Detecting network parameters."
[d168a46]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."
[62e3bcf]840                exit 1
841        fi
[d168a46]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
[03cfd6e]845                        NETMASK[i]=$(LANG=C ifconfig $dev | \
846                                                awk '/Mask/ {sub(/.*:/,"",$4); print $4}
847                                                     /netmask/ {print $4}')
[d168a46]848                        NETBROAD[i]=$(ip -o addr show dev $dev | awk '$3~/inet$/ {print ($6)}')
[826d576]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}')
[d168a46]851                        DEFAULTDEV=${DEFAULTDEV:-"$dev"}
852                fi
[ce85ae8]853                let i++
[d168a46]854        done
[a555f49]855        DNSIP=$(awk '/nameserver/ {print $2}' /etc/resolv.conf | head -n1)
[03cfd6e]856        if [ -z "${NETIP[*]}" -o -z "${NETMASK[*]}" ]; then
[62e3bcf]857                errorAndLog "${FUNCNAME}(): Network not detected."
[7586ca3]858                exit 1
859        fi
[cc7eab7]860
861        # Variables de ejecución de Apache
862        # - APACHE_RUN_USER
863        # - APACHE_RUN_GROUP
[d168a46]864        if [ -f $APACHECFGDIR/envvars ]; then
865                source $APACHECFGDIR/envvars
[cc7eab7]866        fi
[d168a46]867        APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
868        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
[73a1bd6]869
870        echoAndLog "${FUNCNAME}(): Default network device: $DEFAULTDEV."
[7586ca3]871}
872
873
874############################################################
[892606b9]875### Esqueleto para el Servicio pxe y contenedor tftpboot ###
876############################################################
877
[e0edc14]878function tftpConfigure()
879{
[109e8b2]880        echoAndLog "${FUNCNAME}(): Configuring TFTP service."
881        # Habilitar TFTP y reiniciar Inetd.
[8244351]882        if [ -n "$TFTPSERV" ]; then
[584b103]883                if [ -f $INETDCFGDIR/$TFTPSERV ]; then
884                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/$TFTPSERV
885                else
886                        service=$TFTPSERV
[b8969db]887                        $ENABLESERVICE; $STARTSERVICE
[584b103]888                fi
[8244351]889        fi
[53fba30]890        service=$INETDSERV
891        $ENABLESERVICE; $STARTSERVICE
[892606b9]892
[beaebf8]893        # Copiar ficheros de Syslinux.
[297df16]894        cp -a $SYSLINUXDIR $TFTPCFGDIR/syslinux
[beaebf8]895
[297df16]896        # comprobamos el servicio tftp
897        sleep 1
898        testPxe
[892606b9]899}
900
[0a735488]901# Comprueba que haya conexión al servicio TFTP/PXE.
[e0edc14]902function testPxe ()
903{
[297df16]904        echoAndLog "${FUNCNAME}(): Checking TFTP service... please wait."
[beaebf8]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
[e4b1572]908}
909
910
911########################################################################
[5f21d34]912## Configuración servicio Samba
[8fc9552]913########################################################################
[e4b1572]914
915# Configurar servicios Samba.
[8fc9552]916function smbConfigure()
917{
[e0edc14]918        echoAndLog "${FUNCNAME}(): Configuring Samba service."
[8fc9552]919
[d168a46]920        backupFile $SAMBACFGDIR/smb.conf
[8fc9552]921       
[5f21d34]922        # Copiar plantailla de recursos para OpenGnsys
[c1e00e4]923        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
[d168a46]924                $WORKDIR/opengnsys/server/etc/smb-og.conf.tmpl > $SAMBACFGDIR/smb-og.conf
[813f617]925        # Configurar y recargar Samba"
[5f21d34]926        perl -pi -e "s/WORKGROUP/OPENGNSYS/; s/server string \=.*/server string \= OpenGnsys Samba Server/" $SAMBACFGDIR/smb.conf
[03cfd6e]927        if ! grep -q "smb-og" $SAMBACFGDIR/smb.conf; then
928                echo "include = $SAMBACFGDIR/smb-og.conf" >> $SAMBACFGDIR/smb.conf
929        fi
[53fba30]930        service=$SAMBASERV
931        $ENABLESERVICE; $STARTSERVICE
[8fc9552]932        if [ $? -ne 0 ]; then
[813f617]933                errorAndLog "${FUNCNAME}(): error while configure Samba"
[8fc9552]934                return 1
935        fi
[eb9424f]936        # Crear clave para usuario de acceso a los recursos.
[813f617]937        echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | smbpasswd -a -s $OPENGNSYS_CLIENT_USER
[8fc9552]938
[813f617]939        echoAndLog "${FUNCNAME}(): Added Samba configuration."
[8fc9552]940        return 0
941}
942
943
[b6906f7]944########################################################################
[5f21d34]945## Configuración servicio Rsync
[e70925a]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
[4666588]966                if [ -f /etc/default/rsync ]; then
967                        perl -pi -e 's/RSYNC_ENABLE=.*/RSYNC_ENABLE=inetd/' /etc/default/rsync
968                fi
[f243a47]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
[e70925a]986                service=$RSYNCSERV $ENABLESERVICE
987                service=$INETDSERV $STARTSERVICE
988        fi
989
990        echoAndLog "${FUNCNAME}(): Added Rsync configuration."
991        return 0
992}
993
994       
995########################################################################
[5f21d34]996## Configuración servicio DHCP
[b6906f7]997########################################################################
998
[e4b1572]999# Configurar servicios DHCP.
[7586ca3]1000function dhcpConfigure()
1001{
[836a7597]1002        echoAndLog "${FUNCNAME}(): Sample DHCP configuration."
[a555f49]1003
[d168a46]1004        local errcode=0
1005        local i=0
1006        local dev=""
1007
1008        backupFile $DHCPCFGDIR/dhcpd.conf
1009        for dev in ${DEVICE[*]}; do
[01a9904]1010                if [ -n "${SERVERIP[i]}" ]; then
[d168a46]1011                        backupFile $DHCPCFGDIR/dhcpd-$dev.conf
[e4b1572]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" \
[d168a46]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
[b25fc47]1023                errorAndLog "${FUNCNAME}(): error while configuring DHCP server"
[a555f49]1024                return 1
1025        fi
[d168a46]1026        ln -f $DHCPCFGDIR/dhcpd-$DEFAULTDEV.conf $DHCPCFGDIR/dhcpd.conf
[53fba30]1027        service=$DHCPSERV
1028        $ENABLESERVICE; $STARTSERVICE
[d168a46]1029        echoAndLog "${FUNCNAME}(): Sample DHCP configured in \"$DHCPCFGDIR\"."
[a555f49]1030        return 0
[892606b9]1031}
1032
1033
[a01156a]1034#####################################################################
1035####### Funciones específicas de la instalación de Opengnsys
1036#####################################################################
1037
[5f21d34]1038# Copiar ficheros del OpenGnsys Web Console.
[7586ca3]1039function installWebFiles()
1040{
[2b793a8]1041        local COMPATDIR f
[7829e4e]1042        local XAJAXFILE="xajax_0.5_standard.zip"
1043        local SLIMFILE="slim-2.6.1.zip"
[8b8e948]1044        local SWAGGERFILE="swagger-ui-2.2.5.zip"
[2b793a8]1045
[dce072b]1046        echoAndLog "${FUNCNAME}(): Installing web files..."
[2b793a8]1047        # Copiar ficheros.
1048        cp -a $WORKDIR/opengnsys/admin/WebConsole/* $INSTALL_TARGET/www   #*/ comentario para Doxygen.
[7586ca3]1049        if [ $? != 0 ]; then
[dce072b]1050                errorAndLog "${FUNCNAME}(): Error copying web files."
[7586ca3]1051                exit 1
1052        fi
1053        find $INSTALL_TARGET/www -name .svn -type d -exec rm -fr {} \; 2>/dev/null
[7829e4e]1054
[8b8e948]1055        # Descomprimir librerías: XAJAX, Slim y Swagger-UI.
[7829e4e]1056        unzip -o $WORKDIR/opengnsys/admin/$XAJAXFILE -d $INSTALL_TARGET/www/xajax
1057        unzip -o $WORKDIR/opengnsys/admin/$SLIMFILE -d $INSTALL_TARGET/www/rest
[8b8e948]1058        unzip -o $WORKDIR/opengnsys/admin/$SWAGGERFILE -d $INSTALL_TARGET/www/rest
[7829e4e]1059
[2b793a8]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
[7586ca3]1066        # Cambiar permisos para ficheros especiales.
[e6d22c6]1067        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/images/{fotos,iconos}
[b7bd0df]1068        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/tmp/
[aad50e2]1069        # Fichero de logs del agente OGAgent.
[b1735a7]1070        touch $INSTALL_TARGET/log/ogagent.log
1071        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/log/ogagent.log
[2b793a8]1072
[dce072b]1073        echoAndLog "${FUNCNAME}(): Web files installed successfully."
[7586ca3]1074}
1075
1076# Configuración específica de Apache.
[73a1bd6]1077function installWebConsoleApacheConf()
[a01156a]1078{
1079        if [ $# -ne 2 ]; then
[dce072b]1080                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]1081                exit 1
1082        fi
1083
[f9e3393]1084        local path_opengnsys_base="$1"
1085        local path_apache2_confd="$2"
[30837bb]1086        local CONSOLEDIR=${path_opengnsys_base}/www
[a01156a]1087
[892606b9]1088        if [ ! -d $path_apache2_confd ]; then
[dce072b]1089                errorAndLog "${FUNCNAME}(): path to apache2 conf.d can not found, verify your server installation"
[892606b9]1090                return 1
1091        fi
1092
[7586ca3]1093        mkdir -p $path_apache2_confd/{sites-available,sites-enabled}
[892606b9]1094
[dce072b]1095        echoAndLog "${FUNCNAME}(): creating apache2 config file.."
[a01156a]1096
[3ce53a7]1097        # Activar HTTPS.
[7825e9e]1098        $APACHESSLMOD
[643ca8c]1099        $APACHEENABLESSL
1100        $APACHEMAKECERT
[7829e4e]1101        # Activar módulo Rewrite.
1102        $APACHEREWRITEMOD
[d725a41]1103
[30837bb]1104        # Genera configuración de consola web a partir del fichero plantilla.
[f9e3393]1105        if [ -n "$(apachectl -v | grep "2\.[0-2]")" ]; then
1106                # Configuración para versiones anteriores de Apache.
1107                sed -e "s/CONSOLEDIR/${CONSOLEDIR//\//\\/}/g" \
[f3dde7e]1108                        $WORKDIR/opengnsys/server/etc/apache-prev2.4.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}
[f9e3393]1109        else
1110                # Configuración específica a partir de Apache 2.4
1111                sed -e "s/CONSOLEDIR/${CONSOLEDIR//\//\\/}/g" \
[f3dde7e]1112                        $WORKDIR/opengnsys/server/etc/apache.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf
[f9e3393]1113        fi
[643ca8c]1114        $APACHEENABLEOG
[a01156a]1115        if [ $? -ne 0 ]; then
[dce072b]1116                errorAndLog "${FUNCNAME}(): config file can't be linked to apache conf, verify your server installation"
[a01156a]1117                return 1
1118        else
[dce072b]1119                echoAndLog "${FUNCNAME}(): config file created and linked, restarting apache daemon"
[53fba30]1120                service=$APACHESERV
1121                $ENABLESERVICE; $STARTSERVICE
[a01156a]1122                return 0
1123        fi
1124}
1125
[8fc9552]1126
[5d6bf97]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."
[ead38fb]1135                return 1
[5d6bf97]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
[a01156a]1143# Crea la estructura base de la instalación de opengnsys
[eb9424f]1144function createDirs()
[a01156a]1145{
1146        if [ $# -ne 1 ]; then
[dce072b]1147                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]1148                exit 1
1149        fi
1150
[eb9424f]1151        local path_opengnsys_base="$1"
[a01156a]1152
[eb9424f]1153        # Crear estructura de directorios.
[dce072b]1154        echoAndLog "${FUNCNAME}(): creating directory paths in $path_opengnsys_base"
[a01156a]1155        mkdir -p $path_opengnsys_base
1156        mkdir -p $path_opengnsys_base/bin
[5c33840]1157        mkdir -p $path_opengnsys_base/client
[49c6891]1158        mkdir -p $path_opengnsys_base/doc
[5c33840]1159        mkdir -p $path_opengnsys_base/etc
[a01156a]1160        mkdir -p $path_opengnsys_base/lib
[1cc5697]1161        mkdir -p $path_opengnsys_base/log/clients
[eb9424f]1162        ln -fs $path_opengnsys_base/log /var/log/opengnsys
[7586ca3]1163        mkdir -p $path_opengnsys_base/sbin
[a01156a]1164        mkdir -p $path_opengnsys_base/www
[5c33840]1165        mkdir -p $path_opengnsys_base/images
[87c7b02]1166        mkdir -p $TFTPCFGDIR
[63fd1ba]1167        ln -fs $TFTPCFGDIR $path_opengnsys_base/tftpboot
[cfad47b]1168        mkdir -p $path_opengnsys_base/tftpboot/menu.lst
[a01156a]1169        if [ $? -ne 0 ]; then
[dce072b]1170                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
[a01156a]1171                return 1
1172        fi
1173
[eb9424f]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
[5f21d34]1178                echoAndLog "${FUNCNAME}(): creating OpenGnsys user"
[eb9424f]1179                useradd $OPENGNSYS_CLIENT_USER 2>/dev/null
1180                if [ $? -ne 0 ]; then
[5f21d34]1181                        errorAndLog "${FUNCNAME}(): error creating OpenGnsys user"
[eb9424f]1182                        return 1
1183                fi
1184        fi
1185
1186        # Establecer los permisos básicos.
1187        echoAndLog "${FUNCNAME}(): setting directory permissions"
[5eb61a6]1188        chmod -R 775 $path_opengnsys_base/{log/clients,images}
1189        chown -R :$OPENGNSYS_CLIENT_USER $path_opengnsys_base/{log/clients,images}
[eb9424f]1190        if [ $? -ne 0 ]; then
1191                errorAndLog "${FUNCNAME}(): error while setting permissions"
1192                return 1
1193        fi
1194
[7669bca]1195        # Mover el fichero de registro de instalación al directorio de logs.
[acfb07d]1196        echoAndLog "${FUNCNAME}(): moving installation log file"
1197        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
[7669bca]1198        chmod 600 $LOG_FILE
[acfb07d]1199
[dce072b]1200        echoAndLog "${FUNCNAME}(): directory paths created"
[a01156a]1201        return 0
1202}
1203
[463a1d49]1204# Copia ficheros de configuración y ejecutables genéricos del servidor.
[73a1bd6]1205function copyServerFiles ()
[e0edc14]1206{
[463a1d49]1207        if [ $# -ne 1 ]; then
[879689f]1208                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[463a1d49]1209                exit 1
1210        fi
1211
[7caf5a7c]1212        local path_opengnsys_base="$1"
[463a1d49]1213
[a43e90d]1214        # Lista de ficheros y directorios origen y de directorios destino.
[cfad47b]1215        local SOURCES=( server/tftpboot \
[7caf5a7c]1216                        server/bin \
1217                        repoman/bin \
[3e7d77b]1218                        server/lib \
[42a0e41]1219                        admin/Sources/Services/ogAdmServerAux
1220                        admin/Sources/Services/ogAdmRepoAux
[7caf5a7c]1221                        installer/opengnsys_uninstall.sh \
1222                        installer/opengnsys_update.sh \
[6777e3e]1223                        installer/opengnsys_export.sh \
1224                        installer/opengnsys_import.sh \
[7caf5a7c]1225                        doc )
[cfad47b]1226        local TARGETS=( tftpboot \
[7caf5a7c]1227                        bin \
1228                        bin \
[3e7d77b]1229                        lib \
[42a0e41]1230                        sbin \
1231                        sbin \
[7caf5a7c]1232                        lib \
1233                        lib \
[6777e3e]1234                        lib \
1235                        lib \
[7caf5a7c]1236                        doc )
[463a1d49]1237
1238        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
[879689f]1239                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
[463a1d49]1240                exit 1
1241        fi
1242
[a43e90d]1243        # Copiar ficheros.
[879689f]1244        echoAndLog "${FUNCNAME}(): copying files to server directories"
[f2bb433]1245
[8457092]1246        pushd $WORKDIR/opengnsys
[463a1d49]1247        local i
1248        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
1249                if [ -f "${SOURCES[$i]}" ]; then
[879689f]1250                        echoAndLog "Copying ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
[b5aae72]1251                        cp -a "${SOURCES[$i]}" "${path_opengnsys_base}/${TARGETS[$i]}"
[8457092]1252                elif [ -d "${SOURCES[$i]}" ]; then
[879689f]1253                        echoAndLog "Copying content of ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
[8457092]1254                        cp -a "${SOURCES[$i]}"/* "${path_opengnsys_base}/${TARGETS[$i]}"
1255        else
[346eaee]1256                        warningAndLog "Unable to copy ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
[463a1d49]1257                fi
1258        done
[a43e90d]1259
[7586ca3]1260        popd
[892606b9]1261}
1262
[7586ca3]1263####################################################################
[5eb61a6]1264### Funciones de compilación de código fuente de servicios
[7586ca3]1265####################################################################
1266
[5f21d34]1267# Compilar los servicios de OpenGnsys
[7586ca3]1268function servicesCompilation ()
1269{
[13a01a7]1270        local hayErrores=0
[0795938]1271
[5f21d34]1272        # Compilar OpenGnsys Server
1273        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Server"
[7b61735]1274        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
[d168a46]1275        make && mv ogAdmServer $INSTALL_TARGET/sbin
[13a01a7]1276        if [ $? -ne 0 ]; then
[5f21d34]1277                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Server"
[13a01a7]1278                hayErrores=1
1279        fi
[7586ca3]1280        popd
[5f21d34]1281        # Compilar OpenGnsys Repository Manager
1282        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Repository Manager"
[7b61735]1283        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo
[d168a46]1284        make && mv ogAdmRepo $INSTALL_TARGET/sbin
[13a01a7]1285        if [ $? -ne 0 ]; then
[5f21d34]1286                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Repository Manager"
[13a01a7]1287                hayErrores=1
1288        fi
[8125e7c]1289        popd
[5f21d34]1290        # Compilar OpenGnsys Agent
1291        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Agent"
[7b61735]1292        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
[d168a46]1293        make && mv ogAdmAgent $INSTALL_TARGET/sbin
[4984660]1294        if [ $? -ne 0 ]; then
[5f21d34]1295                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Agent"
[4984660]1296                hayErrores=1
1297        fi
1298        popd   
[5f21d34]1299        # Compilar OpenGnsys Client
1300        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Client"
[7b61735]1301        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
[2338c95f]1302        make && mv ogAdmClient ../../../../client/shared/bin
[13a01a7]1303        if [ $? -ne 0 ]; then
[5f21d34]1304                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Client"
[13a01a7]1305                hayErrores=1
1306        fi
[318efac]1307        popd
[13a01a7]1308
1309        return $hayErrores
[b6906f7]1310}
1311
[7b61735]1312####################################################################
1313### Funciones de copia de la Interface de administración
1314####################################################################
1315
1316# Copiar carpeta de Interface
[c1e00e4]1317function copyInterfaceAdm ()
[7b61735]1318{
1319        local hayErrores=0
1320       
[fbd9bcc]1321        # Crear carpeta y copiar Interface
[7b61735]1322        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
[fbd9bcc]1323        cp -ar $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client/interfaceAdm
[7b61735]1324        if [ $? -ne 0 ]; then
1325                echoAndLog "${FUNCNAME}(): error while copying Administration Interface Folder"
1326                hayErrores=1
1327        fi
[b6f1726]1328        chown $OPENGNSYS_CLIENT_USER:$OPENGNSYS_CLIENT_USER $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
[f6c1d2b]1329        chmod 700 $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
[7b61735]1330
1331        return $hayErrores
1332}
[b6906f7]1333
[892606b9]1334####################################################################
1335### Funciones instalacion cliente opengnsys
1336####################################################################
1337
[73a1bd6]1338function copyClientFiles()
[7586ca3]1339{
[d168a46]1340        local errstatus=0
[a555f49]1341
[5f21d34]1342        echoAndLog "${FUNCNAME}(): Copying OpenGnsys Client files."
[73a1bd6]1343        cp -a $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
[d47d38d]1344        if [ $? -ne 0 ]; then
[9ef8920]1345                errorAndLog "${FUNCNAME}(): error while copying client estructure"
[d168a46]1346                errstatus=1
[9ef8920]1347        fi
[d47d38d]1348        find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null
[9ef8920]1349       
[5f21d34]1350        echoAndLog "${FUNCNAME}(): Copying OpenGnsys Cloning Engine files."
[d47d38d]1351        mkdir -p $INSTALL_TARGET/client/lib/engine/bin
[73a1bd6]1352        cp -a $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
[a555f49]1353        if [ $? -ne 0 ]; then
1354                errorAndLog "${FUNCNAME}(): error while copying engine files"
[d168a46]1355                errstatus=1
[a555f49]1356        fi
[9ef8920]1357       
[d168a46]1358        if [ $errstatus -eq 0 ]; then
[9ef8920]1359                echoAndLog "${FUNCNAME}(): client copy files success."
1360        else
1361                errorAndLog "${FUNCNAME}(): client copy files with errors"
1362        fi
1363
[d168a46]1364        return $errstatus
[463a1d49]1365}
1366
1367
[5f21d34]1368# Crear cliente OpenGnsys.
[5ad5dcc]1369function clientCreate()
[813f617]1370{
[89179ff]1371        local DOWNLOADURL="http://$OPENGNSYS_SERVER/downloads"
[ad69c61]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
[0b85cc93]1374        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
[d168a46]1375 
[79c26a8]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}(): Loading Client"
1382                wget $DOWNLOADURL/$FILENAME -O $TARGETFILE
1383        fi
[0b85cc93]1384        if [ ! -s $TARGETFILE ]; then
[a482a77]1385                errorAndLog "${FUNCNAME}(): Error loading OpenGnsys Client"
[813f617]1386                return 1
1387        fi
[1893b9d]1388
[79c26a8]1389        # Montar imagen, copiar cliente ogclient y desmontar.
[5ad5dcc]1390        echoAndLog "${FUNCNAME}(): Copying Client files"
[6ef01d9]1391        echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | \
[1893b9d]1392                        $INSTALL_TARGET/bin/installoglive $TARGETFILE
1393        # Adaptar permisos.
[beaebf8]1394        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/tftpboot/menu.lst
[6ef01d9]1395
[813f617]1396        echoAndLog "${FUNCNAME}(): Client generation success"
1397}
1398
1399
[5f21d34]1400# Configuración básica de servicios de OpenGnsys
[cc7eab7]1401function openGnsysConfigure()
1402{
[d168a46]1403        local i=0
1404        local dev=""
[7d4ce64]1405        local CONSOLEURL
[d168a46]1406
[9ee62ad]1407        echoAndLog "${FUNCNAME}(): Copying init files."
[42a0e41]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
[b8969db]1410        # Deshabilitar servicios de BitTorrent si no están instalados.
1411        if [ ! -e /usr/bin/bttrack ]; then
[fdab5d0]1412                sed -i 's/RUN_BTTRACKER="yes"/RUN_BTTRACKER="no"/; s/RUN_BTSEEDER="yes"/RUN_BTSEEDER="no"/' \
[b8969db]1413                        /etc/default/opengnsys
1414        fi
[9ee62ad]1415        echoAndLog "${FUNCNAME}(): Creating cron files."
[57cf15b]1416        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
[9ee62ad]1417        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
[8fc9552]1418        echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
[dc762088]1419        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
[d168a46]1420
[700299b]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
[5f21d34]1425        echoAndLog "${FUNCNAME}(): Creating OpenGnsys config files."
[d168a46]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" \
[f9b5714]1434                            -e "s/REPOKEY/$OPENGNSYS_REPOKEY/g" \
[d168a46]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
[1a2fa9d8]1441                        CONSOLEURL="https://${SERVERIP[i]}/opengnsys"
[d168a46]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" \
[b22305e]1446                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
[d168a46]1447                                $INSTALL_TARGET/www/controlacceso.php > $INSTALL_TARGET/www/controlacceso-$dev.php
1448                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
[d7f8305]1449                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
[d168a46]1450                                $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient/ogAdmClient.cfg > $INSTALL_TARGET/client/etc/ogAdmClient-$dev.cfg
[7d4ce64]1451                        if [ "$dev" == "$DEFAULTDEV" ]; then
[1a2fa9d8]1452                                OPENGNSYS_CONSOLEURL="$CONSOLEURL"
[7d4ce64]1453                        fi
[d168a46]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
[1f7b2d0]1466
[a3855dc]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
[1f7b2d0]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
[4e19f13]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
[5f21d34]1487        echoAndLog "${FUNCNAME}(): Starting OpenGnsys services."
[53fba30]1488        service="opengnsys"
1489        $ENABLESERVICE; $STARTSERVICE
[cc7eab7]1490}
1491
[b6906f7]1492
[a01156a]1493#####################################################################
[180a07dd]1494#######  Función de resumen informativo de la instalación
1495#####################################################################
1496
[813f617]1497function installationSummary()
1498{
[eb9424f]1499        # Crear fichero de versión y revisión, si no existe.
1500        local VERSIONFILE="$INSTALL_TARGET/doc/VERSION.txt"
[5f21d34]1501        [ -f $VERSIONFILE ] || echo "OpenGnsys Server" >$VERSIONFILE
[130bdbf]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
[eb9424f]1508
1509        # Mostrar información.
[180a07dd]1510        echo
[5f21d34]1511        echoAndLog "OpenGnsys Installation Summary"
[180a07dd]1512        echo       "=============================="
[eb9424f]1513        echoAndLog "Project version:                  $(cat $VERSIONFILE 2>/dev/null)"
[49c6891]1514        echoAndLog "Installation directory:           $INSTALL_TARGET"
[acfb07d]1515        echoAndLog "Installation log file:            $LOG_FILE"
[49c6891]1516        echoAndLog "Repository directory:             $INSTALL_TARGET/images"
[d168a46]1517        echoAndLog "DHCP configuration directory:     $DHCPCFGDIR"
[87c7b02]1518        echoAndLog "TFTP configuration directory:     $TFTPCFGDIR"
1519        echoAndLog "Samba configuration directory:    $SAMBACFGDIR"
[49c6891]1520        echoAndLog "Web Console URL:                  $OPENGNSYS_CONSOLEURL"
[35b0ef1]1521        echoAndLog "Web Console access data:          specified in installer script"
[b8969db]1522        if grep -q "^RUN_BTTRACK.*no" /etc/default/opengnsys; then
1523                echoAndLog "BitTorrent service is disabled."
1524        fi
[180a07dd]1525        echo
1526        echoAndLog "Post-Installation Instructions:"
1527        echo       "==============================="
[663c6625]1528        echoAndLog "Firewall service has been disabled and SELinux mode set to"
[5f21d34]1529        echoAndLog "   permissive during OpenGnsys installation. Please check"
[64f4ada]1530        echoAndLog "   ${FIREWALLSERV:-firewall} and SELinux configuration, if needed."
[4faafcd]1531        echoAndLog "It's strongly recommended to synchronize this server with an NTP server."
[180a07dd]1532        echoAndLog "Review or edit all configuration files."
[c5ce04c]1533        echoAndLog "Insert DHCP configuration data and restart service."
[af5efd6]1534        echoAndLog "Optional: Log-in as Web Console admin user."
1535        echoAndLog " - Review default Organization data and assign access to users."
[180a07dd]1536        echoAndLog "Log-in as Web Console organization user."
[5f21d34]1537        echoAndLog " - Insert OpenGnsys data (labs, computers, menus, etc)."
[180a07dd]1538echo
1539}
1540
1541
1542
1543#####################################################################
[5f21d34]1544####### Proceso de instalación de OpenGnsys
[a01156a]1545#####################################################################
1546
[5f21d34]1547echoAndLog "OpenGnsys installation begins at $(date)"
[6090a2d]1548pushd $WORKDIR
[cc7eab7]1549
[af5efd6]1550# Detectar datos iniciales de auto-configuración del instalador.
[d168a46]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
[07c3a59]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
[7586ca3]1567
[5f21d34]1568# Detener servicios de OpenGnsys, si están activos previamente.
[e0edc14]1569[ -f /etc/init.d/opengnsys ] && /etc/init.d/opengnsys stop
1570
[318efac]1571# Actualizar repositorios
[83518d5]1572updatePackageList
[318efac]1573
[b6906f7]1574# Instalación de dependencias (paquetes de sistema operativo).
[a01156a]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
[109e8b2]1584if [ -n "$INSTALLEXTRADEPS" ]; then
1585        echoAndLog "Installing extra dependencies"
1586        for (( i=0; i<${#INSTALLEXTRADEPS[*]}; i++ )); do
1587                eval ${INSTALLEXTRADEPS[i]}
1588        done
1589fi     
[a01156a]1590
[ff6c349]1591# Detectar datos de auto-configuración después de instalar paquetes.
1592autoConfigurePost
1593
[5f21d34]1594# Arbol de directorios de OpenGnsys.
[eb9424f]1595createDirs ${INSTALL_TARGET}
[a01156a]1596if [ $? -ne 0 ]; then
1597        errorAndLog "Error while creating directory paths!"
1598        exit 1
1599fi
[b6906f7]1600
[1e7eaab]1601# Si es necesario, descarga el repositorio de código en directorio temporal
[49c6891]1602if [ $USESVN -eq 1 ]; then
[1e7eaab]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
[a01156a]1610fi
1611
[5f21d34]1612# Compilar código fuente de los servicios de OpenGnsys.
[b6906f7]1613servicesCompilation
[13a01a7]1614if [ $? -ne 0 ]; then
1615        errorAndLog "Error while compiling OpenGnsys services"
1616        exit 1
1617fi
[b6906f7]1618
[7b61735]1619# Copiar carpeta Interface entre administración y motor de clonación.
[c1e00e4]1620copyInterfaceAdm
[7b61735]1621if [ $? -ne 0 ]; then
[c1e00e4]1622        errorAndLog "Error while copying Administration Interface"
[7b61735]1623        exit 1
1624fi
1625
[e70925a]1626# Configuración de TFTP.
[318efac]1627tftpConfigure
[b6906f7]1628
[e70925a]1629# Configuración de Samba.
[8fc9552]1630smbConfigure
1631if [ $? -ne 0 ]; then
[c1e00e4]1632        errorAndLog "Error while configuring Samba server!"
[8fc9552]1633        exit 1
1634fi
1635
[e70925a]1636# Configuración de Rsync.
1637rsyncConfigure
1638
1639# Configuración ejemplo DHCP.
[b6906f7]1640dhcpConfigure
[a555f49]1641if [ $? -ne 0 ]; then
1642        errorAndLog "Error while copying your dhcp server files!"
1643        exit 1
1644fi
[b6906f7]1645
[5f21d34]1646# Copiar ficheros de servicios OpenGnsys Server.
[73a1bd6]1647copyServerFiles ${INSTALL_TARGET}
[463a1d49]1648if [ $? -ne 0 ]; then
1649        errorAndLog "Error while copying the server files!"
1650        exit 1
1651fi
1652
[5f21d34]1653# Instalar base de datos de OpenGnsys Admin.
[5cc52295]1654isInArray notinstalled "mysql-server" || isInArray notinstalled "mariadb-server"
[b6906f7]1655if [ $? -eq 0 ]; then
[094ac0d]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.
[0f8100d]1664        $STARTSERVICE
[094ac0d]1665        # Asignar clave del usuario "root".
[09bf701]1666        mysqlSetRootPassword "${MYSQL_ROOT_PASSWORD}"
[b6906f7]1667else
[094ac0d]1668        # Si ya está instalado el gestor de bases de datos, obtener clave de "root",
[b6906f7]1669        mysqlGetRootPassword
1670fi
[463a1d49]1671
[09bf701]1672mysqlTestConnection "${MYSQL_ROOT_PASSWORD}"
[a01156a]1673if [ $? -ne 0 ]; then
1674        errorAndLog "Error while connection to mysql"
1675        exit 1
1676fi
[09bf701]1677mysqlDbExists ${OPENGNSYS_DATABASE}
[a01156a]1678if [ $? -ne 0 ]; then
[cc7eab7]1679        echoAndLog "Creating Web Console database"
[09bf701]1680        mysqlCreateDb ${OPENGNSYS_DATABASE}
[a01156a]1681        if [ $? -ne 0 ]; then
[cc7eab7]1682                errorAndLog "Error while creating Web Console database"
[a01156a]1683                exit 1
1684        fi
1685else
[cc7eab7]1686        echoAndLog "Web Console database exists, ommiting creation"
[a01156a]1687fi
1688
[09bf701]1689mysqlCheckUserExists ${OPENGNSYS_DB_USER}
[a01156a]1690if [ $? -ne 0 ]; then
1691        echoAndLog "Creating user in database"
[09bf701]1692        mysqlCreateAdminUserToDb ${OPENGNSYS_DATABASE} ${OPENGNSYS_DB_USER} "${OPENGNSYS_DB_PASSWD}"
[a01156a]1693        if [ $? -ne 0 ]; then
[cc7eab7]1694                errorAndLog "Error while creating database user"
[a01156a]1695                exit 1
1696        fi
1697
1698fi
1699
[09bf701]1700mysqlCheckDbIsEmpty ${OPENGNSYS_DATABASE}
[a01156a]1701if [ $? -eq 0 ]; then
1702        echoAndLog "Creating tables..."
[892606b9]1703        if [ -f $WORKDIR/$OPENGNSYS_DB_CREATION_FILE ]; then
[09bf701]1704                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_CREATION_FILE
[a01156a]1705        else
[892606b9]1706                errorAndLog "Unable to locate $WORKDIR/$OPENGNSYS_DB_CREATION_FILE!!"
[a01156a]1707                exit 1
1708        fi
[bc7dfe7]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)
[295b4ab]1713        OPENGNSYS_DB_UPDATE_FILE="opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
1714        if [ -f $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE ]; then
[bc7dfe7]1715                echoAndLog "Updating tables from version $INSTVERSION to $REPOVERSION"
[09bf701]1716                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE
[bc7dfe7]1717        else
1718                echoAndLog "Database unchanged."
1719        fi
[a01156a]1720fi
[09bf701]1721# Eliminar fichero temporal con credenciales de acceso a MySQL.
1722rm -f $TMPMYCNF
[a01156a]1723
[5f21d34]1724# Copiando páqinas web.
[7586ca3]1725installWebFiles
[5d6bf97]1726# Generar páqinas web de documentación de la API
1727makeDoxygenFiles
[a01156a]1728
[5f21d34]1729# Creando configuración de Apache.
[5fcf180]1730installWebConsoleApacheConf $INSTALL_TARGET $APACHECFGDIR
[a01156a]1731if [ $? -ne 0 ]; then
[5f21d34]1732        errorAndLog "Error configuring Apache for OpenGnsys Admin"
[a01156a]1733        exit 1
1734fi
1735
1736popd
[892606b9]1737
[9ef8920]1738# Crear la estructura de los accesos al servidor desde el cliente (shared)
[73a1bd6]1739copyClientFiles
[9ef8920]1740if [ $? -ne 0 ]; then
1741        errorAndLog "Error creating client structure"
1742fi
1743
[5f21d34]1744# Crear la estructura del cliente de OpenGnsys.
[5ad5dcc]1745clientCreate
[a555f49]1746if [ $? -ne 0 ]; then
[813f617]1747        errorAndLog "Error creating client"
[a555f49]1748        exit 1
1749fi
[892606b9]1750
[5f21d34]1751# Configuración de servicios de OpenGnsys
[65245d1]1752openGnsysConfigure
1753
[180a07dd]1754# Mostrar sumario de la instalación e instrucciones de post-instalación.
1755installationSummary
1756
[077dd7c5]1757#rm -rf $WORKDIR
[5f21d34]1758echoAndLog "OpenGnsys installation finished at $(date)"
[05d2e03]1759exit 0
[2308fc7]1760
Note: See TracBrowser for help on using the repository browser.