source: installer/opengnsys_installer.sh @ b584da5

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 b584da5 was 1893b9d, checked in by ramon <ramongomez@…>, 9 years ago

#729: Usar script installoglive en los procesos de instalación y actualización.

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

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