source: installer/opengnsys_installer.sh @ 4af842a

opengnsys-1.1.0
Last change on this file since 4af842a was 7332a3f, checked in by ramon <ramongomez@…>, 7 years ago

#730: Copiar OpenGnsys 1.1.0 en rama tags/opengnsys-1.1.0

git-svn-id: https://opengnsys.es/svn/tags/opengnsys-1.1.0@5607 a21b9725-9963-47de-94b9-378ad31fedc9

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