source: installer/opengnsys_installer.sh @ 4a511f81

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 4a511f81 was e6574b0, checked in by ramon <ramongomez@…>, 9 years ago

#730: Revisión correcta de ogLive 1.1.0-rc3.

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

  • Property mode set to 100755
File size: 55.4 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{
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
[8e0f770]651        # Claves aleatorias para acceso a las APIs REST.
[7829e4e]652        local OPENGNSYS_APIKEY=$(php -r 'echo md5(uniqid(rand(), true));')
[f9b5714]653        OPENGNSYS_REPOKEY=$(php -r 'echo md5(uniqid(rand(), true));')
[a01156a]654
655        if [ ! -f $sqlfile ]; then
[c5ce04c]656                errorAndLog "${FUNCNAME}(): Unable to locate $sqlfile!!"
[a01156a]657                return 1
658        fi
659
[d168a46]660        echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..."
[c4321ae]661        chmod 600 $tmpfile
[d168a46]662        for dev in ${DEVICE[*]}; do
[73a1bd6]663                if [ "${DEVICE[i]}" == "$DEFAULTDEV" ]; then
[d168a46]664                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
665                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
666                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
[7829e4e]667                            -e "s/APIKEY/$OPENGNSYS_APIKEY/g" \
[8e0f770]668                            -e "s/REPOKEY/$OPENGNSYS_REPOKEY/g" \
[d168a46]669                                $sqlfile > $tmpfile
670                fi
671                let i++
672        done
[09bf701]673        mysql --defaults-extra-file=$TMPMYCNF --default-character-set=utf8 "${database}" < $tmpfile
[c4321ae]674        status=$?
675        rm -f $tmpfile
676        if [ $status -ne 0 ]; then
[c5ce04c]677                errorAndLog "${FUNCNAME}(): error while importing $sqlfile in database $database"
[a01156a]678                return 1
679        fi
[c5ce04c]680        echoAndLog "${FUNCNAME}(): file imported to database $database"
[a01156a]681        return 0
682}
683
684# Crea la base de datos
685function mysqlCreateDb()
686{
[09bf701]687        if [ $# -ne 1 ]; then
[a555f49]688                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]689                exit 1
690        fi
691
[09bf701]692        local database="$1"
[a01156a]693
[a555f49]694        echoAndLog "${FUNCNAME}(): creating database..."
[09bf701]695        mysqladmin --defaults-extra-file=$TMPMYCNF create $database
[a01156a]696        if [ $? -ne 0 ]; then
[a555f49]697                errorAndLog "${FUNCNAME}(): error while creating database $database"
[a01156a]698                return 1
699        fi
[a555f49]700        echoAndLog "${FUNCNAME}(): database $database created"
[a01156a]701        return 0
702}
703
[0a735488]704# Comprueba si ya está definido el usuario de acceso a la BD.
[a01156a]705function mysqlCheckUserExists()
706{
[09bf701]707        if [ $# -ne 1 ]; then
[e0edc14]708                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]709                exit 1
710        fi
711
[09bf701]712        local userdb="$1"
[a01156a]713
[e0edc14]714        echoAndLog "${FUNCNAME}(): checking if $userdb exists..."
[09bf701]715        echo "select user from user where user='${userdb}'\\G" |mysql --defaults-extra-file=$TMPMYCNF mysql | grep user
[a01156a]716        if [ $? -ne 0 ]; then
[e0edc14]717                echoAndLog "${FUNCNAME}(): user doesn't exists"
[a01156a]718                return 1
719        else
[e0edc14]720                echoAndLog "${FUNCNAME}(): user already exists"
[a01156a]721                return 0
722        fi
723
724}
725
726# Crea un usuario administrativo para la base de datos
727function mysqlCreateAdminUserToDb()
728{
[09bf701]729        if [ $# -ne 3 ]; then
[e0edc14]730                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]731                exit 1
732        fi
733
[09bf701]734        local database="$1"
735        local userdb="$2"
736        local passdb="$3"
[a01156a]737
[e0edc14]738        echoAndLog "${FUNCNAME}(): creating admin user ${userdb} to database ${database}"
[a01156a]739
740        cat > $WORKDIR/create_${database}.sql <<EOF
741GRANT USAGE ON *.* TO '${userdb}'@'localhost' IDENTIFIED BY '${passdb}' ;
742GRANT ALL PRIVILEGES ON ${database}.* TO '${userdb}'@'localhost' WITH GRANT OPTION ;
743FLUSH PRIVILEGES ;
744EOF
[09bf701]745        mysql --defaults-extra-file=$TMPMYCNF < $WORKDIR/create_${database}.sql
[a01156a]746        if [ $? -ne 0 ]; then
[e0edc14]747                errorAndLog "${FUNCNAME}(): error while creating user in mysql"
[a01156a]748                rm -f $WORKDIR/create_${database}.sql
749                return 1
750        else
[e0edc14]751                echoAndLog "${FUNCNAME}(): user created ok"
[a01156a]752                rm -f $WORKDIR/create_${database}.sql
753                return 0
754        fi
755}
756
757
758#####################################################################
759####### Funciones para el manejo de Subversion
760#####################################################################
761
[0a735488]762# Obtiene el código fuente del proyecto desde el servidor SVN.
[13a01a7]763function svnExportCode()
764{
765        if [ $# -ne 1 ]; then
766                errorAndLog "${FUNCNAME}(): invalid number of parameters"
767                exit 1
768        fi
769
[6090a2d]770        local url="$1"
[13a01a7]771
772        echoAndLog "${FUNCNAME}(): downloading subversion code..."
773
[6090a2d]774        svn export --force "$url" opengnsys
[13a01a7]775        if [ $? -ne 0 ]; then
[5f21d34]776                errorAndLog "${FUNCNAME}(): error getting OpenGnsys code from $url"
[13a01a7]777                return 1
778        fi
779        echoAndLog "${FUNCNAME}(): subversion code downloaded"
780        return 0
781}
782
783
[892606b9]784############################################################
[7586ca3]785###  Detectar red
786############################################################
787
[07c3a59]788# Comprobar si existe conexión.
789function checkNetworkConnection()
790{
[09ac3b8]791        echoAndLog "${FUNCNAME}(): Disabling Firewall: $FIREWALLSERV."
792        if [ -n "$FIREWALLSERV" ]; then
793                service=$FIREWALLSERV
[b83843c]794                $STOPSERVICE; $DISABLESERVICE
795        fi
[109e8b2]796
[5f21d34]797        echoAndLog "${FUNCNAME}(): Checking OpenGnsys server conectivity."
[07c3a59]798        OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"www.opengnsys.es"}
[225e859]799        if which wget &>/dev/null; then
800                wget --spider -q $OPENGNSYS_SERVER
801        elif which curl &>/dev/null; then
802                curl --connect-timeout 10 -s $OPENGNSYS_SERVER -o /dev/null
803        else
804                echoAndLog "${FUNCNAME}(): Cannot execute \"wget\" nor \"curl\"."
805                return 1
806        fi
[07c3a59]807}
808
809# Obtener los parámetros de red de la interfaz por defecto.
[7586ca3]810function getNetworkSettings()
811{
[d168a46]812        # Arrays globales definidas:
813        # - DEVICE:     nombres de dispositivos de red activos.
814        # - SERVERIP:   IPs locales del servidor.
815        # - NETIP:      IPs de redes.
816        # - NETMASK:    máscaras de red.
817        # - NETBROAD:   IPs de difusión de redes.
818        # - ROUTERIP:   IPs de routers.
819        # Otras variables globales:
820        # - DEFAULTDEV: dispositivo de red por defecto.
821        # - DNSIP:      IP del servidor DNS principal.
822
823        local i=0
824        local dev=""
825
[109e8b2]826        echoAndLog "${FUNCNAME}(): Detecting network parameters."
[d168a46]827        DEVICE=( $(ip -o link show up | awk '!/loopback/ {sub(/:.*/,"",$2); print $2}') )
828        if [ -z "$DEVICE" ]; then
829                errorAndLog "${FUNCNAME}(): Network devices not detected."
[62e3bcf]830                exit 1
831        fi
[d168a46]832        for dev in ${DEVICE[*]}; do
833                SERVERIP[i]=$(ip -o addr show dev $dev | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4)}')
834                if [ -n "${SERVERIP[i]}" ]; then
[03cfd6e]835                        NETMASK[i]=$(LANG=C ifconfig $dev | \
836                                                awk '/Mask/ {sub(/.*:/,"",$4); print $4}
837                                                     /netmask/ {print $4}')
[d168a46]838                        NETBROAD[i]=$(ip -o addr show dev $dev | awk '$3~/inet$/ {print ($6)}')
[826d576]839                        NETIP[i]=$(ip route | awk -v d="$dev" '$3==d && /src/ {sub (/\/.*/,""); print $1}')
840                        ROUTERIP[i]=$(ip route | awk -v d="$dev" '$1=="default" && $5==d {print $3}')
[d168a46]841                        DEFAULTDEV=${DEFAULTDEV:-"$dev"}
842                fi
[ce85ae8]843                let i++
[d168a46]844        done
[a555f49]845        DNSIP=$(awk '/nameserver/ {print $2}' /etc/resolv.conf | head -n1)
[03cfd6e]846        if [ -z "${NETIP[*]}" -o -z "${NETMASK[*]}" ]; then
[62e3bcf]847                errorAndLog "${FUNCNAME}(): Network not detected."
[7586ca3]848                exit 1
849        fi
[cc7eab7]850
851        # Variables de ejecución de Apache
852        # - APACHE_RUN_USER
853        # - APACHE_RUN_GROUP
[d168a46]854        if [ -f $APACHECFGDIR/envvars ]; then
855                source $APACHECFGDIR/envvars
[cc7eab7]856        fi
[d168a46]857        APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
858        APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
[73a1bd6]859
860        echoAndLog "${FUNCNAME}(): Default network device: $DEFAULTDEV."
[7586ca3]861}
862
863
864############################################################
[892606b9]865### Esqueleto para el Servicio pxe y contenedor tftpboot ###
866############################################################
867
[e0edc14]868function tftpConfigure()
869{
[109e8b2]870        echoAndLog "${FUNCNAME}(): Configuring TFTP service."
871        # Habilitar TFTP y reiniciar Inetd.
[8244351]872        if [ -n "$TFTPSERV" ]; then
[584b103]873                if [ -f $INETDCFGDIR/$TFTPSERV ]; then
874                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/$TFTPSERV
875                else
876                        service=$TFTPSERV
[b8969db]877                        $ENABLESERVICE; $STARTSERVICE
[584b103]878                fi
[8244351]879        fi
[53fba30]880        service=$INETDSERV
881        $ENABLESERVICE; $STARTSERVICE
[892606b9]882
[beaebf8]883        # Copiar ficheros de Syslinux.
[297df16]884        cp -a $SYSLINUXDIR $TFTPCFGDIR/syslinux
[beaebf8]885
[297df16]886        # comprobamos el servicio tftp
887        sleep 1
888        testPxe
[892606b9]889}
890
[0a735488]891# Comprueba que haya conexión al servicio TFTP/PXE.
[e0edc14]892function testPxe ()
893{
[297df16]894        echoAndLog "${FUNCNAME}(): Checking TFTP service... please wait."
[beaebf8]895        echo "test" >$TFTPCFGDIR/testpxe
896        tftp -v 127.0.0.1 -c get testpxe /tmp/testpxe && echoAndLog "TFTP service is OK." || errorAndLog "TFTP service is down."
897        rm -f $TFTPCFGDIR/testpxe /tmp/testpxe
[e4b1572]898}
899
900
901########################################################################
[5f21d34]902## Configuración servicio Samba
[8fc9552]903########################################################################
[e4b1572]904
905# Configurar servicios Samba.
[8fc9552]906function smbConfigure()
907{
[e0edc14]908        echoAndLog "${FUNCNAME}(): Configuring Samba service."
[8fc9552]909
[d168a46]910        backupFile $SAMBACFGDIR/smb.conf
[8fc9552]911       
[5f21d34]912        # Copiar plantailla de recursos para OpenGnsys
[c1e00e4]913        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
[d168a46]914                $WORKDIR/opengnsys/server/etc/smb-og.conf.tmpl > $SAMBACFGDIR/smb-og.conf
[813f617]915        # Configurar y recargar Samba"
[5f21d34]916        perl -pi -e "s/WORKGROUP/OPENGNSYS/; s/server string \=.*/server string \= OpenGnsys Samba Server/" $SAMBACFGDIR/smb.conf
[03cfd6e]917        if ! grep -q "smb-og" $SAMBACFGDIR/smb.conf; then
918                echo "include = $SAMBACFGDIR/smb-og.conf" >> $SAMBACFGDIR/smb.conf
919        fi
[53fba30]920        service=$SAMBASERV
921        $ENABLESERVICE; $STARTSERVICE
[8fc9552]922        if [ $? -ne 0 ]; then
[813f617]923                errorAndLog "${FUNCNAME}(): error while configure Samba"
[8fc9552]924                return 1
925        fi
[eb9424f]926        # Crear clave para usuario de acceso a los recursos.
[813f617]927        echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | smbpasswd -a -s $OPENGNSYS_CLIENT_USER
[8fc9552]928
[813f617]929        echoAndLog "${FUNCNAME}(): Added Samba configuration."
[8fc9552]930        return 0
931}
932
933
[b6906f7]934########################################################################
[5f21d34]935## Configuración servicio Rsync
[e70925a]936########################################################################
937
938# Configurar servicio Rsync.
939function rsyncConfigure()
940{
941        echoAndLog "${FUNCNAME}(): Configuring Rsync service."
942
943        backupFile $RSYNCCFGDIR/rsyncd.conf
944
945        # Configurar acceso a Rsync.
946        sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENT_USER/g" \
947                $WORKDIR/opengnsys/repoman/etc/rsyncd.conf.tmpl > $RSYNCCFGDIR/rsyncd.conf
948        sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENT_USER/g" \
949            -e "s/CLIENTPASSWORD/$OPENGNSYS_CLIENT_PASSWD/g" \
950                $WORKDIR/opengnsys/repoman/etc/rsyncd.secrets.tmpl > $RSYNCCFGDIR/rsyncd.secrets
951        chown root.root $RSYNCCFGDIR/rsyncd.secrets
952        chmod 600 $RSYNCCFGDIR/rsyncd.secrets
953
954        # Habilitar Rsync y reiniciar Inetd.
955        if [ -n "$RSYNCSERV" ]; then
[4666588]956                if [ -f /etc/default/rsync ]; then
957                        perl -pi -e 's/RSYNC_ENABLE=.*/RSYNC_ENABLE=inetd/' /etc/default/rsync
958                fi
[f243a47]959                if [ -f $INETDCFGDIR/rsync ]; then
960                        perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/rsync
961                else
962                        cat << EOT > $INETDCFGDIR/rsync
963service rsync
964{
965        disable = no
966        socket_type = stream
967        wait = no
968        user = root
969        server = $(which rsync)
970        server_args = --daemon
971        log_on_failure += USERID
972        flags = IPv6
973}
974EOT
975                fi
[e70925a]976                service=$RSYNCSERV $ENABLESERVICE
977                service=$INETDSERV $STARTSERVICE
978        fi
979
980        echoAndLog "${FUNCNAME}(): Added Rsync configuration."
981        return 0
982}
983
984       
985########################################################################
[5f21d34]986## Configuración servicio DHCP
[b6906f7]987########################################################################
988
[e4b1572]989# Configurar servicios DHCP.
[7586ca3]990function dhcpConfigure()
991{
[836a7597]992        echoAndLog "${FUNCNAME}(): Sample DHCP configuration."
[a555f49]993
[d168a46]994        local errcode=0
995        local i=0
996        local dev=""
997
998        backupFile $DHCPCFGDIR/dhcpd.conf
999        for dev in ${DEVICE[*]}; do
[01a9904]1000                if [ -n "${SERVERIP[i]}" ]; then
[d168a46]1001                        backupFile $DHCPCFGDIR/dhcpd-$dev.conf
[e4b1572]1002                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1003                            -e "s/NETIP/${NETIP[i]}/g" \
1004                            -e "s/NETMASK/${NETMASK[i]}/g" \
1005                            -e "s/NETBROAD/${NETBROAD[i]}/g" \
1006                            -e "s/ROUTERIP/${ROUTERIP[i]}/g" \
[d168a46]1007                            -e "s/DNSIP/$DNSIP/g" \
1008                            $WORKDIR/opengnsys/server/etc/dhcpd.conf.tmpl > $DHCPCFGDIR/dhcpd-$dev.conf || errcode=1
1009                fi
1010                let i++
1011        done
1012        if [ $errcode -ne 0 ]; then
[b25fc47]1013                errorAndLog "${FUNCNAME}(): error while configuring DHCP server"
[a555f49]1014                return 1
1015        fi
[d168a46]1016        ln -f $DHCPCFGDIR/dhcpd-$DEFAULTDEV.conf $DHCPCFGDIR/dhcpd.conf
[53fba30]1017        service=$DHCPSERV
1018        $ENABLESERVICE; $STARTSERVICE
[d168a46]1019        echoAndLog "${FUNCNAME}(): Sample DHCP configured in \"$DHCPCFGDIR\"."
[a555f49]1020        return 0
[892606b9]1021}
1022
1023
[a01156a]1024#####################################################################
1025####### Funciones específicas de la instalación de Opengnsys
1026#####################################################################
1027
[5f21d34]1028# Copiar ficheros del OpenGnsys Web Console.
[7586ca3]1029function installWebFiles()
1030{
[2b793a8]1031        local COMPATDIR f
[7829e4e]1032        local XAJAXFILE="xajax_0.5_standard.zip"
1033        local SLIMFILE="slim-2.6.1.zip"
[2b793a8]1034
[dce072b]1035        echoAndLog "${FUNCNAME}(): Installing web files..."
[2b793a8]1036        # Copiar ficheros.
1037        cp -a $WORKDIR/opengnsys/admin/WebConsole/* $INSTALL_TARGET/www   #*/ comentario para Doxygen.
[7586ca3]1038        if [ $? != 0 ]; then
[dce072b]1039                errorAndLog "${FUNCNAME}(): Error copying web files."
[7586ca3]1040                exit 1
1041        fi
1042        find $INSTALL_TARGET/www -name .svn -type d -exec rm -fr {} \; 2>/dev/null
[7829e4e]1043
1044        # Descomprimir librerías XAJAX y SLIM.
1045        unzip -o $WORKDIR/opengnsys/admin/$XAJAXFILE -d $INSTALL_TARGET/www/xajax
1046        unzip -o $WORKDIR/opengnsys/admin/$SLIMFILE -d $INSTALL_TARGET/www/rest
1047
[2b793a8]1048        # Compatibilidad con dispositivos móviles.
1049        COMPATDIR="$INSTALL_TARGET/www/principal"
1050        for f in acciones administracion aula aulas hardwares imagenes menus repositorios softwares; do
1051                sed 's/clickcontextualnodo/clicksupnodo/g' $COMPATDIR/$f.php > $COMPATDIR/$f.device.php
1052        done
1053        cp -a $COMPATDIR/imagenes.device.php $COMPATDIR/imagenes.device4.php
[7586ca3]1054        # Cambiar permisos para ficheros especiales.
[e6d22c6]1055        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/images/{fotos,iconos}
[b7bd0df]1056        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/tmp/
[aad50e2]1057        # Fichero de logs del agente OGAgent.
[b1735a7]1058        touch $INSTALL_TARGET/log/ogagent.log
1059        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/log/ogagent.log
[2b793a8]1060
[dce072b]1061        echoAndLog "${FUNCNAME}(): Web files installed successfully."
[7586ca3]1062}
1063
1064# Configuración específica de Apache.
[73a1bd6]1065function installWebConsoleApacheConf()
[a01156a]1066{
1067        if [ $# -ne 2 ]; then
[dce072b]1068                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]1069                exit 1
1070        fi
1071
[f9e3393]1072        local path_opengnsys_base="$1"
1073        local path_apache2_confd="$2"
[30837bb]1074        local CONSOLEDIR=${path_opengnsys_base}/www
[a01156a]1075
[892606b9]1076        if [ ! -d $path_apache2_confd ]; then
[dce072b]1077                errorAndLog "${FUNCNAME}(): path to apache2 conf.d can not found, verify your server installation"
[892606b9]1078                return 1
1079        fi
1080
[7586ca3]1081        mkdir -p $path_apache2_confd/{sites-available,sites-enabled}
[892606b9]1082
[dce072b]1083        echoAndLog "${FUNCNAME}(): creating apache2 config file.."
[a01156a]1084
[3ce53a7]1085        # Activar HTTPS.
[7825e9e]1086        $APACHESSLMOD
[643ca8c]1087        $APACHEENABLESSL
1088        $APACHEMAKECERT
[7829e4e]1089        # Activar módulo Rewrite.
1090        $APACHEREWRITEMOD
[d725a41]1091
[30837bb]1092        # Genera configuración de consola web a partir del fichero plantilla.
[f9e3393]1093        if [ -n "$(apachectl -v | grep "2\.[0-2]")" ]; then
1094                # Configuración para versiones anteriores de Apache.
1095                sed -e "s/CONSOLEDIR/${CONSOLEDIR//\//\\/}/g" \
[f3dde7e]1096                        $WORKDIR/opengnsys/server/etc/apache-prev2.4.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}
[f9e3393]1097        else
1098                # Configuración específica a partir de Apache 2.4
1099                sed -e "s/CONSOLEDIR/${CONSOLEDIR//\//\\/}/g" \
[f3dde7e]1100                        $WORKDIR/opengnsys/server/etc/apache.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf
[f9e3393]1101        fi
[643ca8c]1102        $APACHEENABLEOG
[a01156a]1103        if [ $? -ne 0 ]; then
[dce072b]1104                errorAndLog "${FUNCNAME}(): config file can't be linked to apache conf, verify your server installation"
[a01156a]1105                return 1
1106        else
[dce072b]1107                echoAndLog "${FUNCNAME}(): config file created and linked, restarting apache daemon"
[53fba30]1108                service=$APACHESERV
1109                $ENABLESERVICE; $STARTSERVICE
[a01156a]1110                return 0
1111        fi
1112}
1113
[8fc9552]1114
[5d6bf97]1115# Crear documentación Doxygen para la consola web.
1116function makeDoxygenFiles()
1117{
1118        echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
1119        $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
1120                        $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
1121        if [ ! -d "$INSTALL_TARGET/www/html" ]; then
1122                errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
[ead38fb]1123                return 1
[5d6bf97]1124        fi
1125        mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
1126        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/api
1127        echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
1128}
1129
1130
[a01156a]1131# Crea la estructura base de la instalación de opengnsys
[eb9424f]1132function createDirs()
[a01156a]1133{
1134        if [ $# -ne 1 ]; then
[dce072b]1135                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[a01156a]1136                exit 1
1137        fi
1138
[eb9424f]1139        local path_opengnsys_base="$1"
[a01156a]1140
[eb9424f]1141        # Crear estructura de directorios.
[dce072b]1142        echoAndLog "${FUNCNAME}(): creating directory paths in $path_opengnsys_base"
[a01156a]1143        mkdir -p $path_opengnsys_base
1144        mkdir -p $path_opengnsys_base/bin
[5c33840]1145        mkdir -p $path_opengnsys_base/client
[49c6891]1146        mkdir -p $path_opengnsys_base/doc
[5c33840]1147        mkdir -p $path_opengnsys_base/etc
[a01156a]1148        mkdir -p $path_opengnsys_base/lib
[1cc5697]1149        mkdir -p $path_opengnsys_base/log/clients
[eb9424f]1150        ln -fs $path_opengnsys_base/log /var/log/opengnsys
[7586ca3]1151        mkdir -p $path_opengnsys_base/sbin
[a01156a]1152        mkdir -p $path_opengnsys_base/www
[5c33840]1153        mkdir -p $path_opengnsys_base/images
[87c7b02]1154        mkdir -p $TFTPCFGDIR
[63fd1ba]1155        ln -fs $TFTPCFGDIR $path_opengnsys_base/tftpboot
[cfad47b]1156        mkdir -p $path_opengnsys_base/tftpboot/menu.lst
[a01156a]1157        if [ $? -ne 0 ]; then
[dce072b]1158                errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
[a01156a]1159                return 1
1160        fi
1161
[eb9424f]1162        # Crear usuario ficticio.
1163        if id -u $OPENGNSYS_CLIENT_USER &>/dev/null; then
1164                echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENT_USER\" is already created"
1165        else
[5f21d34]1166                echoAndLog "${FUNCNAME}(): creating OpenGnsys user"
[eb9424f]1167                useradd $OPENGNSYS_CLIENT_USER 2>/dev/null
1168                if [ $? -ne 0 ]; then
[5f21d34]1169                        errorAndLog "${FUNCNAME}(): error creating OpenGnsys user"
[eb9424f]1170                        return 1
1171                fi
1172        fi
1173
1174        # Establecer los permisos básicos.
1175        echoAndLog "${FUNCNAME}(): setting directory permissions"
[5eb61a6]1176        chmod -R 775 $path_opengnsys_base/{log/clients,images}
1177        chown -R :$OPENGNSYS_CLIENT_USER $path_opengnsys_base/{log/clients,images}
[eb9424f]1178        if [ $? -ne 0 ]; then
1179                errorAndLog "${FUNCNAME}(): error while setting permissions"
1180                return 1
1181        fi
1182
[7669bca]1183        # Mover el fichero de registro de instalación al directorio de logs.
[acfb07d]1184        echoAndLog "${FUNCNAME}(): moving installation log file"
1185        mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
[7669bca]1186        chmod 600 $LOG_FILE
[acfb07d]1187
[dce072b]1188        echoAndLog "${FUNCNAME}(): directory paths created"
[a01156a]1189        return 0
1190}
1191
[463a1d49]1192# Copia ficheros de configuración y ejecutables genéricos del servidor.
[73a1bd6]1193function copyServerFiles ()
[e0edc14]1194{
[463a1d49]1195        if [ $# -ne 1 ]; then
[879689f]1196                errorAndLog "${FUNCNAME}(): invalid number of parameters"
[463a1d49]1197                exit 1
1198        fi
1199
[7caf5a7c]1200        local path_opengnsys_base="$1"
[463a1d49]1201
[a43e90d]1202        # Lista de ficheros y directorios origen y de directorios destino.
[cfad47b]1203        local SOURCES=( server/tftpboot \
[7caf5a7c]1204                        server/bin \
1205                        repoman/bin \
[42a0e41]1206                        admin/Sources/Services/ogAdmServerAux
1207                        admin/Sources/Services/ogAdmRepoAux
[7caf5a7c]1208                        installer/opengnsys_uninstall.sh \
1209                        installer/opengnsys_update.sh \
1210                        doc )
[cfad47b]1211        local TARGETS=( tftpboot \
[7caf5a7c]1212                        bin \
1213                        bin \
[42a0e41]1214                        sbin \
1215                        sbin \
[7caf5a7c]1216                        lib \
1217                        lib \
1218                        doc )
[463a1d49]1219
1220        if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
[879689f]1221                errorAndLog "${FUNCNAME}(): inconsistent number of array items"
[463a1d49]1222                exit 1
1223        fi
1224
[a43e90d]1225        # Copiar ficheros.
[879689f]1226        echoAndLog "${FUNCNAME}(): copying files to server directories"
[f2bb433]1227
[8457092]1228        pushd $WORKDIR/opengnsys
[463a1d49]1229        local i
1230        for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
1231                if [ -f "${SOURCES[$i]}" ]; then
[879689f]1232                        echoAndLog "Copying ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
[b5aae72]1233                        cp -a "${SOURCES[$i]}" "${path_opengnsys_base}/${TARGETS[$i]}"
[8457092]1234                elif [ -d "${SOURCES[$i]}" ]; then
[879689f]1235                        echoAndLog "Copying content of ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
[8457092]1236                        cp -a "${SOURCES[$i]}"/* "${path_opengnsys_base}/${TARGETS[$i]}"
1237        else
[346eaee]1238                        warningAndLog "Unable to copy ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
[463a1d49]1239                fi
1240        done
[a43e90d]1241
[7586ca3]1242        popd
[892606b9]1243}
1244
[7586ca3]1245####################################################################
[5eb61a6]1246### Funciones de compilación de código fuente de servicios
[7586ca3]1247####################################################################
1248
[5f21d34]1249# Compilar los servicios de OpenGnsys
[7586ca3]1250function servicesCompilation ()
1251{
[13a01a7]1252        local hayErrores=0
[0795938]1253
[5f21d34]1254        # Compilar OpenGnsys Server
1255        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Server"
[7b61735]1256        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
[d168a46]1257        make && mv ogAdmServer $INSTALL_TARGET/sbin
[13a01a7]1258        if [ $? -ne 0 ]; then
[5f21d34]1259                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Server"
[13a01a7]1260                hayErrores=1
1261        fi
[7586ca3]1262        popd
[5f21d34]1263        # Compilar OpenGnsys Repository Manager
1264        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Repository Manager"
[7b61735]1265        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo
[d168a46]1266        make && mv ogAdmRepo $INSTALL_TARGET/sbin
[13a01a7]1267        if [ $? -ne 0 ]; then
[5f21d34]1268                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Repository Manager"
[13a01a7]1269                hayErrores=1
1270        fi
[8125e7c]1271        popd
[5f21d34]1272        # Compilar OpenGnsys Agent
1273        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Agent"
[7b61735]1274        pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
[d168a46]1275        make && mv ogAdmAgent $INSTALL_TARGET/sbin
[4984660]1276        if [ $? -ne 0 ]; then
[5f21d34]1277                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Agent"
[4984660]1278                hayErrores=1
1279        fi
1280        popd   
[5f21d34]1281        # Compilar OpenGnsys Client
1282        echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Client"
[7b61735]1283        pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
[2338c95f]1284        make && mv ogAdmClient ../../../../client/shared/bin
[13a01a7]1285        if [ $? -ne 0 ]; then
[5f21d34]1286                echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Client"
[13a01a7]1287                hayErrores=1
1288        fi
[318efac]1289        popd
[13a01a7]1290
1291        return $hayErrores
[b6906f7]1292}
1293
[7b61735]1294####################################################################
1295### Funciones de copia de la Interface de administración
1296####################################################################
1297
1298# Copiar carpeta de Interface
[c1e00e4]1299function copyInterfaceAdm ()
[7b61735]1300{
1301        local hayErrores=0
1302       
[fbd9bcc]1303        # Crear carpeta y copiar Interface
[7b61735]1304        echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
[fbd9bcc]1305        cp -ar $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client/interfaceAdm
[7b61735]1306        if [ $? -ne 0 ]; then
1307                echoAndLog "${FUNCNAME}(): error while copying Administration Interface Folder"
1308                hayErrores=1
1309        fi
[b6f1726]1310        chown $OPENGNSYS_CLIENT_USER:$OPENGNSYS_CLIENT_USER $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
[f6c1d2b]1311        chmod 700 $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
[7b61735]1312
1313        return $hayErrores
1314}
[b6906f7]1315
[892606b9]1316####################################################################
1317### Funciones instalacion cliente opengnsys
1318####################################################################
1319
[73a1bd6]1320function copyClientFiles()
[7586ca3]1321{
[d168a46]1322        local errstatus=0
[a555f49]1323
[5f21d34]1324        echoAndLog "${FUNCNAME}(): Copying OpenGnsys Client files."
[73a1bd6]1325        cp -a $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
[d47d38d]1326        if [ $? -ne 0 ]; then
[9ef8920]1327                errorAndLog "${FUNCNAME}(): error while copying client estructure"
[d168a46]1328                errstatus=1
[9ef8920]1329        fi
[d47d38d]1330        find $INSTALL_TARGET/client -name .svn -type d -exec rm -fr {} \; 2>/dev/null
[9ef8920]1331       
[5f21d34]1332        echoAndLog "${FUNCNAME}(): Copying OpenGnsys Cloning Engine files."
[d47d38d]1333        mkdir -p $INSTALL_TARGET/client/lib/engine/bin
[73a1bd6]1334        cp -a $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
[a555f49]1335        if [ $? -ne 0 ]; then
1336                errorAndLog "${FUNCNAME}(): error while copying engine files"
[d168a46]1337                errstatus=1
[a555f49]1338        fi
[9ef8920]1339       
[d168a46]1340        if [ $errstatus -eq 0 ]; then
[9ef8920]1341                echoAndLog "${FUNCNAME}(): client copy files success."
1342        else
1343                errorAndLog "${FUNCNAME}(): client copy files with errors"
1344        fi
1345
[d168a46]1346        return $errstatus
[463a1d49]1347}
1348
1349
[5f21d34]1350# Crear cliente OpenGnsys.
[5ad5dcc]1351function clientCreate()
[813f617]1352{
[89179ff]1353        local DOWNLOADURL="http://$OPENGNSYS_SERVER/downloads"
[e6574b0]1354        local FILENAME=ogLive-wily-4.2.0-35-generic-r4919.iso           # 1.1.0-rc3
[0b85cc93]1355        local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
[d168a46]1356 
[79c26a8]1357        # Descargar cliente, si es necesario.
1358        if [ -s $PROGRAMDIR/$FILENAME ]; then
1359                echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
1360                mv $PROGRAMDIR/$FILENAME $TARGETFILE
1361        else
1362                echoAndLog "${FUNCNAME}(): Loading Client"
1363                wget $DOWNLOADURL/$FILENAME -O $TARGETFILE
1364        fi
[0b85cc93]1365        if [ ! -s $TARGETFILE ]; then
[a482a77]1366                errorAndLog "${FUNCNAME}(): Error loading OpenGnsys Client"
[813f617]1367                return 1
1368        fi
[1893b9d]1369
[79c26a8]1370        # Montar imagen, copiar cliente ogclient y desmontar.
[5ad5dcc]1371        echoAndLog "${FUNCNAME}(): Copying Client files"
[6ef01d9]1372        echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | \
[1893b9d]1373                        $INSTALL_TARGET/bin/installoglive $TARGETFILE
1374        # Adaptar permisos.
[beaebf8]1375        chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/tftpboot/menu.lst
[6ef01d9]1376
[813f617]1377        echoAndLog "${FUNCNAME}(): Client generation success"
1378}
1379
1380
[5f21d34]1381# Configuración básica de servicios de OpenGnsys
[cc7eab7]1382function openGnsysConfigure()
1383{
[d168a46]1384        local i=0
1385        local dev=""
[7d4ce64]1386        local CONSOLEURL
[d168a46]1387
[9ee62ad]1388        echoAndLog "${FUNCNAME}(): Copying init files."
[42a0e41]1389        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
1390        cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default /etc/default/opengnsys
[b8969db]1391        # Deshabilitar servicios de BitTorrent si no están instalados.
1392        if [ ! -e /usr/bin/bttrack ]; then
[fdab5d0]1393                sed -i 's/RUN_BTTRACKER="yes"/RUN_BTTRACKER="no"/; s/RUN_BTSEEDER="yes"/RUN_BTSEEDER="no"/' \
[b8969db]1394                        /etc/default/opengnsys
1395        fi
[9ee62ad]1396        echoAndLog "${FUNCNAME}(): Creating cron files."
[57cf15b]1397        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
[9ee62ad]1398        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
[8fc9552]1399        echo "5 * * * *   root   [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
[dc762088]1400        echo "* * * * *   root   [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
[d168a46]1401
[700299b]1402        echoAndLog "${FUNCNAME}(): Creating logrotate configuration file."
1403        sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
1404                $WORKDIR/opengnsys/server/etc/logrotate.tmpl > /etc/logrotate.d/opengnsys
1405
[5f21d34]1406        echoAndLog "${FUNCNAME}(): Creating OpenGnsys config files."
[d168a46]1407        for dev in ${DEVICE[*]}; do
1408                if [ -n "${SERVERIP[i]}" ]; then
1409                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1410                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1411                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1412                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
1413                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer/ogAdmServer.cfg > $INSTALL_TARGET/etc/ogAdmServer-$dev.cfg
1414                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
[f9b5714]1415                            -e "s/REPOKEY/$OPENGNSYS_REPOKEY/g" \
[d168a46]1416                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmRepo/ogAdmRepo.cfg > $INSTALL_TARGET/etc/ogAdmRepo-$dev.cfg
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" \
1421                                $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent/ogAdmAgent.cfg > $INSTALL_TARGET/etc/ogAdmAgent-$dev.cfg
[1a2fa9d8]1422                        CONSOLEURL="https://${SERVERIP[i]}/opengnsys"
[d168a46]1423                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
1424                            -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
1425                            -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
1426                            -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
[b22305e]1427                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
[d168a46]1428                                $INSTALL_TARGET/www/controlacceso.php > $INSTALL_TARGET/www/controlacceso-$dev.php
1429                        sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
[d7f8305]1430                            -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
[d168a46]1431                                $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient/ogAdmClient.cfg > $INSTALL_TARGET/client/etc/ogAdmClient-$dev.cfg
[7d4ce64]1432                        if [ "$dev" == "$DEFAULTDEV" ]; then
[1a2fa9d8]1433                                OPENGNSYS_CONSOLEURL="$CONSOLEURL"
[7d4ce64]1434                        fi
[d168a46]1435                fi
1436                let i++
1437        done
1438        ln -f $INSTALL_TARGET/etc/ogAdmServer-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmServer.cfg
1439        ln -f $INSTALL_TARGET/etc/ogAdmRepo-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmRepo.cfg
1440        ln -f $INSTALL_TARGET/etc/ogAdmAgent-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmAgent.cfg
1441        ln -f $INSTALL_TARGET/client/etc/ogAdmClient-$DEFAULTDEV.cfg $INSTALL_TARGET/client/etc/ogAdmClient.cfg
1442        ln -f $INSTALL_TARGET/www/controlacceso-$DEFAULTDEV.php $INSTALL_TARGET/www/controlacceso.php
1443        chown root:root $INSTALL_TARGET/etc/{ogAdmServer,ogAdmAgent}*.cfg
1444        chmod 600 $INSTALL_TARGET/etc/{ogAdmServer,ogAdmAgent}*.cfg
1445        chown $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/controlacceso*.php
1446        chmod 600 $INSTALL_TARGET/www/controlacceso*.php
[1f7b2d0]1447
[a3855dc]1448        # Configuración del motor de clonación.
1449        # - Zona horaria del servidor.
1450        TZ=$(timedatectl status|awk -F"[:()]" '/Time.*zone/ {print $2}')
1451        cat << EOT >> $INSTALL_TARGET/client/etc/engine.cfg
1452# OpenGnsys Server timezone.
1453TZ="${TZ// /}"
1454EOT
1455
[1f7b2d0]1456        # Revisar permisos generales.
1457        if [ -x $INSTALL_TARGET/bin/checkperms ]; then
1458                echoAndLog "${FUNCNAME}(): Checking permissions."
1459                OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENT_USER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" $INSTALL_TARGET/bin/checkperms
1460        fi
1461
[4e19f13]1462        # Evitar inicio de duplicado en Ubuntu 14.04 (Upstart y SysV Init).
1463        if [ -f /etc/init/${MYSQLSERV}.conf ]; then
1464                service=$MYSQLSERV
1465                $DISABLESERVICE
1466        fi
1467
[5f21d34]1468        echoAndLog "${FUNCNAME}(): Starting OpenGnsys services."
[53fba30]1469        service="opengnsys"
1470        $ENABLESERVICE; $STARTSERVICE
[cc7eab7]1471}
1472
[b6906f7]1473
[a01156a]1474#####################################################################
[180a07dd]1475#######  Función de resumen informativo de la instalación
1476#####################################################################
1477
[813f617]1478function installationSummary()
1479{
[eb9424f]1480        # Crear fichero de versión y revisión, si no existe.
1481        local VERSIONFILE="$INSTALL_TARGET/doc/VERSION.txt"
[5f21d34]1482        [ -f $VERSIONFILE ] || echo "OpenGnsys Server" >$VERSIONFILE
[130bdbf]1483        # Incluir datos de revisión, si se está instaladno desde el repositorio
1484        # de código o si no está incluida en el fichero de versión.
1485        if [ $USESVN -eq 1 ] || [ -z "$(awk '$3~/r[0-9]*/ {print}' $VERSIONFILE)" ]; then
1486                local REVISION=$(LANG=C svn info $SVN_URL|awk '/Rev:/ {print "r"$4}')
1487                perl -pi -e "s/($| r[0-9]*)/ $REVISION/" $VERSIONFILE
1488        fi
[eb9424f]1489
1490        # Mostrar información.
[180a07dd]1491        echo
[5f21d34]1492        echoAndLog "OpenGnsys Installation Summary"
[180a07dd]1493        echo       "=============================="
[eb9424f]1494        echoAndLog "Project version:                  $(cat $VERSIONFILE 2>/dev/null)"
[49c6891]1495        echoAndLog "Installation directory:           $INSTALL_TARGET"
[acfb07d]1496        echoAndLog "Installation log file:            $LOG_FILE"
[49c6891]1497        echoAndLog "Repository directory:             $INSTALL_TARGET/images"
[d168a46]1498        echoAndLog "DHCP configuration directory:     $DHCPCFGDIR"
[87c7b02]1499        echoAndLog "TFTP configuration directory:     $TFTPCFGDIR"
1500        echoAndLog "Samba configuration directory:    $SAMBACFGDIR"
[49c6891]1501        echoAndLog "Web Console URL:                  $OPENGNSYS_CONSOLEURL"
[35b0ef1]1502        echoAndLog "Web Console access data:          specified in installer script"
[b8969db]1503        if grep -q "^RUN_BTTRACK.*no" /etc/default/opengnsys; then
1504                echoAndLog "BitTorrent service is disabled."
1505        fi
[180a07dd]1506        echo
1507        echoAndLog "Post-Installation Instructions:"
1508        echo       "==============================="
[663c6625]1509        echoAndLog "Firewall service has been disabled and SELinux mode set to"
[5f21d34]1510        echoAndLog "   permissive during OpenGnsys installation. Please check"
[64f4ada]1511        echoAndLog "   ${FIREWALLSERV:-firewall} and SELinux configuration, if needed."
[4faafcd]1512        echoAndLog "It's strongly recommended to synchronize this server with an NTP server."
[180a07dd]1513        echoAndLog "Review or edit all configuration files."
[c5ce04c]1514        echoAndLog "Insert DHCP configuration data and restart service."
[af5efd6]1515        echoAndLog "Optional: Log-in as Web Console admin user."
1516        echoAndLog " - Review default Organization data and assign access to users."
[180a07dd]1517        echoAndLog "Log-in as Web Console organization user."
[5f21d34]1518        echoAndLog " - Insert OpenGnsys data (labs, computers, menus, etc)."
[180a07dd]1519echo
1520}
1521
1522
1523
1524#####################################################################
[5f21d34]1525####### Proceso de instalación de OpenGnsys
[a01156a]1526#####################################################################
1527
[5f21d34]1528echoAndLog "OpenGnsys installation begins at $(date)"
[6090a2d]1529pushd $WORKDIR
[cc7eab7]1530
[af5efd6]1531# Detectar datos iniciales de auto-configuración del instalador.
[d168a46]1532autoConfigure
1533
1534# Detectar parámetros de red y comprobar si hay conexión.
1535getNetworkSettings
1536if [ $? -ne 0 ]; then
1537        errorAndLog "Error reading default network settings."
1538        exit 1
1539fi
[07c3a59]1540checkNetworkConnection
1541if [ $? -ne 0 ]; then
1542        errorAndLog "Error connecting to server. Causes:"
1543        errorAndLog " - Network is unreachable, review devices parameters."
1544        errorAndLog " - You are inside a private network, configure the proxy service."
1545        errorAndLog " - Server is temporally down, try agian later."
1546        exit 1
1547fi
[7586ca3]1548
[5f21d34]1549# Detener servicios de OpenGnsys, si están activos previamente.
[e0edc14]1550[ -f /etc/init.d/opengnsys ] && /etc/init.d/opengnsys stop
1551
[318efac]1552# Actualizar repositorios
[83518d5]1553updatePackageList
[318efac]1554
[b6906f7]1555# Instalación de dependencias (paquetes de sistema operativo).
[a01156a]1556declare -a notinstalled
1557checkDependencies DEPENDENCIES notinstalled
1558if [ $? -ne 0 ]; then
1559        installDependencies notinstalled
1560        if [ $? -ne 0 ]; then
1561                echoAndLog "Error while installing some dependeces, please verify your server installation before continue"
1562                exit 1
1563        fi
1564fi
[109e8b2]1565if [ -n "$INSTALLEXTRADEPS" ]; then
1566        echoAndLog "Installing extra dependencies"
1567        for (( i=0; i<${#INSTALLEXTRADEPS[*]}; i++ )); do
1568                eval ${INSTALLEXTRADEPS[i]}
1569        done
1570fi     
[a01156a]1571
[ff6c349]1572# Detectar datos de auto-configuración después de instalar paquetes.
1573autoConfigurePost
1574
[5f21d34]1575# Arbol de directorios de OpenGnsys.
[eb9424f]1576createDirs ${INSTALL_TARGET}
[a01156a]1577if [ $? -ne 0 ]; then
1578        errorAndLog "Error while creating directory paths!"
1579        exit 1
1580fi
[b6906f7]1581
[1e7eaab]1582# Si es necesario, descarga el repositorio de código en directorio temporal
[49c6891]1583if [ $USESVN -eq 1 ]; then
[1e7eaab]1584        svnExportCode $SVN_URL
1585        if [ $? -ne 0 ]; then
1586                errorAndLog "Error while getting code from svn"
1587                exit 1
1588        fi
1589else
1590        ln -fs "$(dirname $PROGRAMDIR)" opengnsys
[a01156a]1591fi
1592
[5f21d34]1593# Compilar código fuente de los servicios de OpenGnsys.
[b6906f7]1594servicesCompilation
[13a01a7]1595if [ $? -ne 0 ]; then
1596        errorAndLog "Error while compiling OpenGnsys services"
1597        exit 1
1598fi
[b6906f7]1599
[7b61735]1600# Copiar carpeta Interface entre administración y motor de clonación.
[c1e00e4]1601copyInterfaceAdm
[7b61735]1602if [ $? -ne 0 ]; then
[c1e00e4]1603        errorAndLog "Error while copying Administration Interface"
[7b61735]1604        exit 1
1605fi
1606
[e70925a]1607# Configuración de TFTP.
[318efac]1608tftpConfigure
[b6906f7]1609
[e70925a]1610# Configuración de Samba.
[8fc9552]1611smbConfigure
1612if [ $? -ne 0 ]; then
[c1e00e4]1613        errorAndLog "Error while configuring Samba server!"
[8fc9552]1614        exit 1
1615fi
1616
[e70925a]1617# Configuración de Rsync.
1618rsyncConfigure
1619
1620# Configuración ejemplo DHCP.
[b6906f7]1621dhcpConfigure
[a555f49]1622if [ $? -ne 0 ]; then
1623        errorAndLog "Error while copying your dhcp server files!"
1624        exit 1
1625fi
[b6906f7]1626
[5f21d34]1627# Copiar ficheros de servicios OpenGnsys Server.
[73a1bd6]1628copyServerFiles ${INSTALL_TARGET}
[463a1d49]1629if [ $? -ne 0 ]; then
1630        errorAndLog "Error while copying the server files!"
1631        exit 1
1632fi
1633
[5f21d34]1634# Instalar base de datos de OpenGnsys Admin.
[5cc52295]1635isInArray notinstalled "mysql-server" || isInArray notinstalled "mariadb-server"
[b6906f7]1636if [ $? -eq 0 ]; then
[094ac0d]1637        # Habilitar gestor de base de datos (MySQL, si falla, MariaDB).
1638        service=$MYSQLSERV
1639        $ENABLESERVICE
1640        if [ $? != 0 ]; then
1641                service=$MARIADBSERV
1642                $ENABLESERVICE
1643        fi
1644        # Activar gestor de base de datos.
[0f8100d]1645        $STARTSERVICE
[094ac0d]1646        # Asignar clave del usuario "root".
[09bf701]1647        mysqlSetRootPassword "${MYSQL_ROOT_PASSWORD}"
[b6906f7]1648else
[094ac0d]1649        # Si ya está instalado el gestor de bases de datos, obtener clave de "root",
[b6906f7]1650        mysqlGetRootPassword
1651fi
[463a1d49]1652
[09bf701]1653mysqlTestConnection "${MYSQL_ROOT_PASSWORD}"
[a01156a]1654if [ $? -ne 0 ]; then
1655        errorAndLog "Error while connection to mysql"
1656        exit 1
1657fi
[09bf701]1658mysqlDbExists ${OPENGNSYS_DATABASE}
[a01156a]1659if [ $? -ne 0 ]; then
[cc7eab7]1660        echoAndLog "Creating Web Console database"
[09bf701]1661        mysqlCreateDb ${OPENGNSYS_DATABASE}
[a01156a]1662        if [ $? -ne 0 ]; then
[cc7eab7]1663                errorAndLog "Error while creating Web Console database"
[a01156a]1664                exit 1
1665        fi
1666else
[cc7eab7]1667        echoAndLog "Web Console database exists, ommiting creation"
[a01156a]1668fi
1669
[09bf701]1670mysqlCheckUserExists ${OPENGNSYS_DB_USER}
[a01156a]1671if [ $? -ne 0 ]; then
1672        echoAndLog "Creating user in database"
[09bf701]1673        mysqlCreateAdminUserToDb ${OPENGNSYS_DATABASE} ${OPENGNSYS_DB_USER} "${OPENGNSYS_DB_PASSWD}"
[a01156a]1674        if [ $? -ne 0 ]; then
[cc7eab7]1675                errorAndLog "Error while creating database user"
[a01156a]1676                exit 1
1677        fi
1678
1679fi
1680
[09bf701]1681mysqlCheckDbIsEmpty ${OPENGNSYS_DATABASE}
[a01156a]1682if [ $? -eq 0 ]; then
1683        echoAndLog "Creating tables..."
[892606b9]1684        if [ -f $WORKDIR/$OPENGNSYS_DB_CREATION_FILE ]; then
[09bf701]1685                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_CREATION_FILE
[a01156a]1686        else
[892606b9]1687                errorAndLog "Unable to locate $WORKDIR/$OPENGNSYS_DB_CREATION_FILE!!"
[a01156a]1688                exit 1
1689        fi
[bc7dfe7]1690else
1691        # Si existe fichero ogBDAdmin-VersLocal-VersRepo.sql; aplicar cambios.
1692        INSTVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt)
1693        REPOVERSION=$(awk '{print $2}' $WORKDIR/opengnsys/doc/VERSION.txt)
[295b4ab]1694        OPENGNSYS_DB_UPDATE_FILE="opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
1695        if [ -f $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE ]; then
[bc7dfe7]1696                echoAndLog "Updating tables from version $INSTVERSION to $REPOVERSION"
[09bf701]1697                mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE
[bc7dfe7]1698        else
1699                echoAndLog "Database unchanged."
1700        fi
[a01156a]1701fi
[09bf701]1702# Eliminar fichero temporal con credenciales de acceso a MySQL.
1703rm -f $TMPMYCNF
[a01156a]1704
[5f21d34]1705# Copiando páqinas web.
[7586ca3]1706installWebFiles
[5d6bf97]1707# Generar páqinas web de documentación de la API
1708makeDoxygenFiles
[a01156a]1709
[5f21d34]1710# Creando configuración de Apache.
[5fcf180]1711installWebConsoleApacheConf $INSTALL_TARGET $APACHECFGDIR
[a01156a]1712if [ $? -ne 0 ]; then
[5f21d34]1713        errorAndLog "Error configuring Apache for OpenGnsys Admin"
[a01156a]1714        exit 1
1715fi
1716
1717popd
[892606b9]1718
[9ef8920]1719# Crear la estructura de los accesos al servidor desde el cliente (shared)
[73a1bd6]1720copyClientFiles
[9ef8920]1721if [ $? -ne 0 ]; then
1722        errorAndLog "Error creating client structure"
1723fi
1724
[5f21d34]1725# Crear la estructura del cliente de OpenGnsys.
[5ad5dcc]1726clientCreate
[a555f49]1727if [ $? -ne 0 ]; then
[813f617]1728        errorAndLog "Error creating client"
[a555f49]1729        exit 1
1730fi
[892606b9]1731
[5f21d34]1732# Configuración de servicios de OpenGnsys
[65245d1]1733openGnsysConfigure
1734
[180a07dd]1735# Mostrar sumario de la instalación e instrucciones de post-instalación.
1736installationSummary
1737
[077dd7c5]1738#rm -rf $WORKDIR
[5f21d34]1739echoAndLog "OpenGnsys installation finished at $(date)"
[05d2e03]1740exit 0
[2308fc7]1741
Note: See TracBrowser for help on using the repository browser.