summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRamón M. Gómez <ramongomez@us.es>2019-05-27 13:36:02 +0200
committerRamón M. Gómez <ramongomez@us.es>2019-05-27 13:36:02 +0200
commitae36b2ec3cb1fa2a2915b17255a5412f1e5ddf90 (patch)
tree0ce329c352297b3c11e95e12a70de103dcffa438
parent5641ae96b36c5551b83e78ae51a126adc0125afb (diff)
#907: Add new scripts to support OpenGnsys 1.1.x and 3.x versions.
-rwxr-xr-xadmin/Interface/InventarioHardware5
-rwxr-xr-xadmin/Interface/InventarioHardware35
-rwxr-xr-xadmin/Interface/InventarioSoftware18
-rwxr-xr-xadmin/Interface/InventarioSoftware35
-rw-r--r--admin/WebConsole3/frontend/src/environments/environment.ts4
-rwxr-xr-xclient/shared/scripts/poweroff2
-rwxr-xr-xclient/shared/scripts/reboot2
-rwxr-xr-xinstaller/opengnsys_installer.sh290
-rwxr-xr-xinstaller/opengnsys_installer3.sh1757
-rwxr-xr-xinstaller/opengnsys_update.sh76
-rwxr-xr-xinstaller/opengnsys_update3.sh1308
-rw-r--r--installer/vagrant/Vagrantfile-webconsole3-vbox4
-rwxr-xr-xserver/bin/checkperms2
-rwxr-xr-xserver/bin/setserveraddr83
-rwxr-xr-xserver/bin/setserveraddr3115
15 files changed, 3468 insertions, 208 deletions
diff --git a/admin/Interface/InventarioHardware b/admin/Interface/InventarioHardware
index 7e889737..17614a5d 100755
--- a/admin/Interface/InventarioHardware
+++ b/admin/Interface/InventarioHardware
@@ -1,5 +1,6 @@
#!/bin/bash
-# Script de interfaz para devolver el inventario de hardware de un cliente.
+# Script de interfaz para guardar en un fichero el inventario de hardware de un cliente.
-listHardwareInfo | tail -n+2
+file=$(listHardwareInfo)
+tail -n+2 $file >$1
diff --git a/admin/Interface/InventarioHardware3 b/admin/Interface/InventarioHardware3
new file mode 100755
index 00000000..7e889737
--- /dev/null
+++ b/admin/Interface/InventarioHardware3
@@ -0,0 +1,5 @@
+#!/bin/bash
+# Script de interfaz para devolver el inventario de hardware de un cliente.
+
+listHardwareInfo | tail -n+2
+
diff --git a/admin/Interface/InventarioSoftware b/admin/Interface/InventarioSoftware
index fd481580..fa96565d 100755
--- a/admin/Interface/InventarioSoftware
+++ b/admin/Interface/InventarioSoftware
@@ -1,5 +1,19 @@
#!/bin/bash
-# Script de interfaz para devolver el inventario de software de un sistema operativo instalado.
-listSoftwareInfo $1 $2
+TIME1=$SECONDS
+
+#Carga el configurador del engine desde el fichero engine.cfg
+[ -z $OGENGINECONFIGURATE ] && source /opt/opengnsys/etc/engine.cfg
+
+# Limpia los ficheros temporales usados como log de seguimiento para httpdlog
+echo -n " " | tee $OGLOGSESSION $OGLOGCOMMAND ${OGLOGCOMMAND}.tmp
+
+# Registro de inicio de ejecución
+ogEcho log session "$MSG_INTERFACE_START $0 $*"
+
+file=$(listSoftwareInfo $1 $2)
+cp $file $3
+
+TIME=$[SECONDS-TIME1]
+ogEcho log session " [ ] $MSG_SCRIPTS_TIME_PARTIAL : $[TIME/60]m $[TIME%60]s"
diff --git a/admin/Interface/InventarioSoftware3 b/admin/Interface/InventarioSoftware3
new file mode 100755
index 00000000..fd481580
--- /dev/null
+++ b/admin/Interface/InventarioSoftware3
@@ -0,0 +1,5 @@
+#!/bin/bash
+# Script de interfaz para devolver el inventario de software de un sistema operativo instalado.
+
+listSoftwareInfo $1 $2
+
diff --git a/admin/WebConsole3/frontend/src/environments/environment.ts b/admin/WebConsole3/frontend/src/environments/environment.ts
index 3ba05adc..6ad91356 100644
--- a/admin/WebConsole3/frontend/src/environments/environment.ts
+++ b/admin/WebConsole3/frontend/src/environments/environment.ts
@@ -107,10 +107,10 @@ export const environment = {
'CREATE_IMAGE': '/opt/opengnsys/interfaceAdm/CrearImagen',
'HISTORY_LOG': '/cgi-bin/httpd-history-log.sh',
'REALTIME_LOG': '/cgi-bin/httpd-log.sh',
- 'SOFTWARE_INVENTORY': '/opt/opengnsys/interfaceAdm/InventarioSoftware',
+ 'SOFTWARE_INVENTORY': '/opt/opengnsys/interfaceAdm/InventarioSoftware3',
'REBOOT': 'reboot 1',
'POWER_OFF': 'poweroff',
- 'HARDWARE_INVENTORY': '/opt/opengnsys/interfaceAdm/InventarioHardware',
+ 'HARDWARE_INVENTORY': '/opt/opengnsys/interfaceAdm/InventarioHardware3',
'REFRESH_INFO': 'sendConfigToServer'
},
themes: ['skin-black', 'skin-black-light', 'skin-blue-light', 'skin-blue', 'skin-green', 'skin-green-light', 'skin-purple', 'skin-purple-light', 'skin-red', 'skin-red-light', 'skin-yellow', 'skin-yellow-light', 'skin-uhu', 'skin-uhu-light']
diff --git a/client/shared/scripts/poweroff b/client/shared/scripts/poweroff
index 563845b3..ad67dfc9 100755
--- a/client/shared/scripts/poweroff
+++ b/client/shared/scripts/poweroff
@@ -30,6 +30,8 @@ ethtool -s $DEVICE wol g 2>/dev/null
BUSYBOX=$(which busyboxOLD)
BUSYBOX=${BUSYBOX:-"busybox"}
+# Retardo para dar lugar al registro en cola de acciones.
+sleep 5
# Parar agente y Browser.
ogagent stop &>/dev/null
pkill -9 browser
diff --git a/client/shared/scripts/reboot b/client/shared/scripts/reboot
index 30362cc7..4bd9b34c 100755
--- a/client/shared/scripts/reboot
+++ b/client/shared/scripts/reboot
@@ -44,6 +44,8 @@ ethtool -s $DEVICE wol g 2>/dev/null
BUSYBOX=$(which busyboxOLD)
BUSYBOX=${BUSYBOX:-"busybox"}
+# Retardo para dar lugar al registro en cola de acciones.
+sleep $TIME
# Parar agente y Browser.
ogagent stop &>/dev/null
pkill -9 browser
diff --git a/installer/opengnsys_installer.sh b/installer/opengnsys_installer.sh
index 297da723..f559552c 100755
--- a/installer/opengnsys_installer.sh
+++ b/installer/opengnsys_installer.sh
@@ -9,8 +9,8 @@
#### AVISO: Puede editar configuración de acceso por defecto.
#### WARNING: Edit default access configuration if you wish.
DEFAULT_MYSQL_ROOT_PASSWORD="passwordroot" # Clave por defecto root de MySQL
-DEFAULT_OPENGNSYS_DB_USER="admin" # Usuario por defecto de acceso a la base de datos
-DEFAULT_OPENGNSYS_DB_PASSWD="admin" # Clave por defecto de acceso a la base de datos
+DEFAULT_OPENGNSYS_DB_USER="usuog" # Usuario por defecto de acceso a la base de datos
+DEFAULT_OPENGNSYS_DB_PASSWD="passusuog" # Clave por defecto de acceso a la base de datos
DEFAULT_OPENGNSYS_CLIENT_PASSWD="og" # Clave por defecto de acceso del cliente
# Sólo ejecutable por usuario root
@@ -123,8 +123,9 @@ LOG_FILE=/tmp/$(basename $OGLOGFILE)
# Usuario del cliente para acceso remoto.
OPENGNSYS_CLIENT_USER="opengnsys"
-# Nombre de la base datos.
-OPENGNSYS_DATABASE="opengnsys"
+# Nombre de la base datos y fichero SQL para su creación.
+OPENGNSYS_DATABASE="ogAdmBD"
+OPENGNSYS_DB_CREATION_FILE=opengnsys/admin/Database/${OPENGNSYS_DATABASE}.sql
#####################################################################
@@ -134,7 +135,7 @@ OPENGNSYS_DATABASE="opengnsys"
# Generar variables de configuración del instalador
# Variables globales:
# - OSDISTRIB, OSVERSION - tipo y versión de la distribución GNU/Linux
-# - PREREQS, DEPENDENCIES - arrays de prerrequisitos y dependencias que deben estar instaladas
+# - DEPENDENCIES - array de dependencias que deben estar instaladas
# - UPDATEPKGLIST, INSTALLPKGS, CHECKPKGS - comandos para gestión de paquetes
# - INSTALLEXTRADEPS - instalar dependencias no incluidas en la distribución
# - STARTSERVICE, ENABLESERVICE - iniciar y habilitar un servicio
@@ -168,10 +169,9 @@ OSVERSION="${OSVERSION%%.*}"
# Configuración según la distribución GNU/Linux (usar minúsculas).
case "$OSDISTRIB" in
ubuntu|debian|linuxmint)
- PREREQS=( curl software-properties-common )
- DEPENDENCIES=( subversion apache2 php php-ldap php-fpm mysql-server php-mysql isc-dhcp-server bittorrent tftp-hpa tftpd-hpa xinetd build-essential g++-multilib libmysqlclient-dev wget doxygen graphviz bittornado ctorrent samba rsync unzip netpipes debootstrap schroot squashfs-tools btrfs-tools procps arp-scan realpath php-curl gettext moreutils jq udpcast libev-dev shim-signed grub-efi-amd64-signed git php-mbstring php-xml nodejs debhelper )
+ DEPENDENCIES=( subversion apache2 php php-ldap php-fpm mysql-server php-mysql isc-dhcp-server bittorrent tftp-hpa tftpd-hpa xinetd build-essential g++-multilib libmysqlclient-dev wget curl doxygen graphviz bittornado ctorrent samba rsync unzip netpipes debootstrap schroot squashfs-tools btrfs-tools procps arp-scan realpath php-curl gettext moreutils jq udpcast libev-dev shim-signed grub-efi-amd64-signed )
UPDATEPKGLIST="apt-get update"
- INSTALLPKG="apt-get -y install"
+ INSTALLPKG="apt-get -y install --force-yes"
CHECKPKG="dpkg -s \$package 2>/dev/null | grep Status | grep -qw install"
if which service &>/dev/null; then
STARTSERVICE="eval service \$service restart"
@@ -188,7 +188,7 @@ case "$OSDISTRIB" in
APACHEOGSITE=opengnsys
APACHEUSER="www-data"
APACHEGROUP="www-data"
- APACHEENABLEMODS="a2enmod ssl rewrite proxy_fcgi actions alias"
+ APACHEENABLEMODS="a2enmod ssl rewrite proxy_fcgi fastcgi actions alias"
APACHEENABLESSL="a2ensite default-ssl"
APACHEENABLEOG="a2ensite $APACHEOGSITE"
APACHEMAKECERT="make-ssl-cert generate-default-snakeoil --force-overwrite"
@@ -206,8 +206,7 @@ case "$OSDISTRIB" in
TFTPCFGDIR=/var/lib/tftpboot
;;
fedora|centos)
- PREREQS=( curl )
- DEPENDENCIES=( subversion httpd mod_ssl php-ldap php-fpm 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 doxygen graphviz ctorrent samba samba-client rsync unzip debootstrap schroot squashfs-tools python-crypto arp-scan procps-ng gettext moreutils jq net-tools udpcast libev-devel shim-x64 grub2-efi-x64 grub2-efi-x64-modules http://ftp.altlinux.org/pub/distributions/ALTLinux/5.1/branch/$(arch)/RPMS.classic/netpipes-4.2-alt1.$(arch).rpm )
+ DEPENDENCIES=( subversion httpd mod_ssl php-ldap php-fpm 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 udpcast libev-devel shim-x64 grub2-efi-x64 grub2-efi-x64-modules http://ftp.altlinux.org/pub/distributions/ALTLinux/5.1/branch/$(arch)/RPMS.classic/netpipes-4.2-alt1.$(arch).rpm )
[ "$OSDISTRIB" == "centos" ] && UPDATEPKGLIST="yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-$OSVERSION.noarch.rpm http://rpms.remirepo.net/enterprise/remi-release-$OSVERSION.rpm"
INSTALLEXTRADEPS=( 'pushd /tmp; wget -t3 http://ftp.acc.umu.se/mirror/bittornado/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' )
INSTALLPKG="yum install -y libstdc++ libstdc++.i686"
@@ -249,10 +248,6 @@ case "$OSDISTRIB" in
*) echo "ERROR: Distribution not supported by OpenGnsys."
exit 1 ;;
esac
-# Instalar Composer y Angular-CLI.
-INSTALLEXTRADEPS=( ${INSTALLEXTRADEPS[@]} \
- 'if [ ! -f /usr/local/bin/composer.phar ]; then php -r "copy(\"https://getcomposer.org/installer\", \"/tmp/composer-setup.php\");"; php /tmp/composer-setup.php --install-dir=/usr/local/bin; rm -f /tmp/composer-setup.php; else /usr/local/bin/composer.phar self-update; fi' \
- 'npm install -g @angular/cli@6.2.3' )
# Fichero de credenciales de acceso a MySQL.
TMPMYCNF=/tmp/.my.cnf.$$
@@ -262,6 +257,8 @@ TMPMYCNF=/tmp/.my.cnf.$$
# Modificar variables de configuración tras instalar paquetes del sistema.
function autoConfigurePost()
{
+local f
+
# Configuraciones específicas para Samba y TFTP en Debian 6.
[ -z "$SYSTEMD" -a ! -e /etc/init.d/$SAMBASERV ] && SAMBASERV=samba
[ ! -e $TFTPCFGDIR ] && TFTPCFGDIR=/srv/tftp
@@ -274,14 +271,12 @@ function updatePackageList()
{
local DHCPVERSION PHP7VERSION
-# Si es necesario, actualizar la lista de paquetes disponibles e instalar prerrequisitos.
+# Si es necesario, actualizar la lista de paquetes disponibles.
[ -n "$UPDATEPKGLIST" ] && eval $UPDATEPKGLIST
-[ ${#PREREQS[@]} -gt 0 ] && eval $INSTALLPKG ${PREREQS[@]}
# Configuración personallizada de algunos paquetes.
case "$OSDISTRIB" in
ubuntu|linuxmint) # Postconfiguación personalizada para Ubuntu.
- # Instalar prerrequisitos.
# Configuración para DHCP v3.
DHCPVERSION=$(apt-cache show $(apt-cache pkgnames|egrep "dhcp.?-server$") | \
awk '/Version/ {print substr($2,1,1);}' | \
@@ -293,9 +288,10 @@ case "$OSDISTRIB" in
fi
# Configuración para PHP 7 en Ubuntu.
if [ -z "$(apt-cache pkgnames php7)" ]; then
+ eval $INSTALLPKG software-properties-common
add-apt-repository -y ppa:ondrej/php
eval $UPDATEPKGLIST
- PHP7VERSION=$(apt-cache pkgnames php7. | sort | tail -1)
+ PHP7VERSION=$(apt-cache pkgnames php7 | sort | head -1)
PHPFPMSERV="${PHP7VERSION}-fpm"
DEPENDENCIES=( ${DEPENDENCIES[@]//php/$PHP7VERSION} )
fi
@@ -303,8 +299,6 @@ case "$OSDISTRIB" in
[ -z "$(apt-cache pkgnames libmysqlclient-dev)" ] && [ -n "$(apt-cache pkgnames libmysqlclient15)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//libmysqlclient-dev/libmysqlclient15} )
# Paquete correcto para realpath.
[ -z "$(apt-cache pkgnames realpath)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//realpath/coreutils} )
- # Instalar NodeJS.
- curl -sL https://deb.nodesource.com/setup_10.x | bash -
;;
centos) # Postconfiguación personalizada para CentOS.
# Configuración para PHP 7.
@@ -318,16 +312,12 @@ case "$OSDISTRIB" in
# Instalar ctorrent de EPEL para CentOS 6 (no disponible en CentOS 7).
DEPENDENCIES=( ${DEPENDENCIES[*]/ctorrent/http://dl.fedoraproject.org/pub/epel/6/$(arch)/Packages/c/ctorrent-1.3.4-14.dnh3.3.2.el6.$(arch).rpm} )
fi
- # Instalar NodeJS.
- curl -sL https://rpm.nodesource.com/setup_10.x | bash -
;;
fedora) # Postconfiguación personalizada para Fedora.
# Incluir paquetes específicos.
DEPENDENCIES=( ${DEPENDENCIES[@]} btrfs-progs )
# Sustituir MySQL por MariaDB a partir de Fedora 20.
[ $OSVERSION -ge 20 ] && DEPENDENCIES=( ${DEPENDENCIES[*]/mysql-/mariadb-} )
- # Instalar NodeJS.
- curl -sL https://rpm.nodesource.com/setup_10.x | bash -
;;
esac
}
@@ -735,20 +725,23 @@ function mysqlCreateDb()
# Comprueba si ya está definido el usuario de acceso a la BD.
function mysqlCheckUserExists()
{
-if [ $# -ne 1 ]; then
- errorAndLog "${FUNCNAME}(): invalid number of parameters"
- exit 1
-fi
-local userdb="$1"
+ if [ $# -ne 1 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local userdb="$1"
+
+ echoAndLog "${FUNCNAME}(): checking if $userdb exists..."
+ echo "select user from user where user='${userdb}'\\G" |mysql --defaults-extra-file=$TMPMYCNF mysql | grep user
+ if [ $? -ne 0 ]; then
+ echoAndLog "${FUNCNAME}(): user doesn't exists"
+ return 1
+ else
+ echoAndLog "${FUNCNAME}(): user already exists"
+ return 0
+ fi
-echoAndLog "${FUNCNAME}(): checking if $userdb exists..."
-if [ "$(mysql --defaults-extra-file=$TMPMYCNF -Nse "SELECT user FROM mysql.user WHERE user='$userdb'")" == "$userdb" ]; then
- echoAndLog "${FUNCNAME}(): user already exists"
- return 0
-else
- echoAndLog "${FUNCNAME}(): user doesn't exists"
- return 1
-fi
}
# Crea un usuario administrativo para la base de datos
@@ -817,9 +810,16 @@ function downloadCode()
# Comprobar si existe conexión.
function checkNetworkConnection()
{
-echoAndLog "${FUNCNAME}(): Checking OpenGnsys server connectivity."
-OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"opengnsys.es"}
-curl --connect-timeout 10 -s $OPENGNSYS_SERVER -o /dev/null
+ echoAndLog "${FUNCNAME}(): Checking OpenGnsys server connectivity."
+ OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"opengnsys.es"}
+ if which wget &>/dev/null; then
+ wget --spider -q $OPENGNSYS_SERVER
+ elif which curl &>/dev/null; then
+ curl --connect-timeout 10 -s $OPENGNSYS_SERVER -o /dev/null
+ else
+ echoAndLog "${FUNCNAME}(): Cannot execute \"wget\" nor \"curl\"."
+ return 1
+ fi
}
# Convierte nº de bits (notación CIDR) en máscara de red (gracias a FriedZombie en openwrt.org).
@@ -1045,70 +1045,37 @@ function dhcpConfigure()
####### Funciones específicas de la instalación de Opengnsys
#####################################################################
-# Instalar OpenGnsys Web Console.
+# Copiar ficheros del OpenGnsys Web Console.
function installWebFiles()
{
-local $tmpdir jsonfile=$INSTALL_TARGET/etc/opengnsys.json
-
-echoAndLog "${FUNCNAME}(): Copying backend files..."
-sed -e "s/ database_name:.*/ database_name: $OPENGNSYS_DATABASE/" \
- -e "s/ database_user:.*/ database_user: $OPENGNSYS_DB_USER/" \
- -e "s/ database_password:.*/ database_password: $OPENGNSYS_DB_PASSWD/" \
- $WORKDIR/opengnsys/admin/WebConsole3/backend/app/config/parameters.yml.dist \
- > $WORKDIR/opengnsys/admin/WebConsole3/backend/app/config/parameters.yml
-chown -R $OPENGNSYS_CLIENT_USER:$OPENGNSYS_CLIENT_USER $WORKDIR/opengnsys/admin/WebConsole3
-cp -a $WORKDIR/opengnsys/admin/WebConsole3/backend $INSTALL_TARGET/www3
-if [ $? != 0 ]; then
- errorAndLog "${FUNCNAME}(): Error copying backend files."
- exit 1
-fi
+ local COMPATDIR f
+ local SLIMFILE="slim-2.6.1.zip"
+ local SWAGGERFILE="swagger-ui-2.2.5.zip"
-echoAndLog "${FUNCNAME}(): Installing backend framework..."
-pushd $INSTALL_TARGET/www3/backend
-sudo -u $OPENGNSYS_CLIENT_USER composer.phar install
-chmod 777 -R var/cache var/logs
-sudo -u $OPENGNSYS_CLIENT_USER php app/console doctrine:database:create --if-not-exists
-sudo -u $OPENGNSYS_CLIENT_USER php app/console doctrine:schema:update --force
-echo yes | php app/console doctrine:fixtures:load
-php app/console fos:user:create "$OPENGNSYS_DB_USER" "${OPENGNSYS_DB_USER}@localhost.localdomain" "$OPENGNSYS_DB_USER"
-# Guardar tokens de seguridad.
-read -e APIID APISECRET <<< \
- "$(php app/console doctrine:query:sql "SELECT random_id, secret FROM og_core__clients WHERE id=1;" | \
- awk -F\" '$2~/^(random_id|secret)$/ {getline; printf("%s ", $2)}')"
-read -e CLIENTID CLIENTSECRET <<< \
- "$(php app/console opengnsys:oauth-server:client:create --no-ansi \
- --grant-type="password" --grant-type="refresh_token" \
- --grant-type="token" \
- --grant-type="http://opengnsys.es/grants/og_client" | \
- awk 'BEGIN {RS=" "}
- /^(id|secret)$/ {getline; gsub(/,/, ""); printf("%s ", $0)}')"
-[ -f $jsonfile ] || echo "{}" > $jsonfile
-jq '.client |= (. + {"id":"'"$CLIENTID"'", "secret":"'"$CLIENTSECRET"'"})' $jsonfile | sponge $jsonfile
-chown root $jsonfile
-chmod 600 $jsonfile
-popd
+ echoAndLog "${FUNCNAME}(): Installing web files..."
+ # Copiar ficheros.
+ cp -a $WORKDIR/opengnsys/admin/WebConsole/* $INSTALL_TARGET/www #*/ comentario para Doxygen.
+ if [ $? != 0 ]; then
+ errorAndLog "${FUNCNAME}(): Error copying web files."
+ exit 1
+ fi
-echoAndLog "${FUNCNAME}(): Installing frontend framework..."
-pushd $WORKDIR/opengnsys/admin/WebConsole3/frontend
-tmpdir=$(sudo -u $OPENGNSYS_CLIENT_USER mktemp -d)
-echo "cache = $tmpdir" > .npmrc
-sudo -u $OPENGNSYS_CLIENT_USER npm install
-sed -i -e "s/SERVERIP/$SERVERIP/" \
- -e "s/CLIENTID/1_$APIID/" \
- -e "s/CLIENTSECRET/$APISECRET/" src/environments/environment.ts
-sed -i 's,base href=.*,base href="/opengnsys3/frontend/">,' src/index.html
-sudo -u $OPENGNSYS_CLIENT_USER ng build
-rm -fr $tmpdir
-
-echoAndLog "${FUNCNAME}(): Copying frontend files..."
-cp -a dist/opengnsysAngular6 $INSTALL_TARGET/www3/frontend
-if [ $? != 0 ]; then
- errorAndLog "${FUNCNAME}(): Error copying frontend files."
- exit 1
-fi
-popd
+ # Descomprimir librerías: Slim y Swagger-UI.
+ unzip -o $WORKDIR/opengnsys/admin/$SLIMFILE -d $INSTALL_TARGET/www/rest
+ unzip -o $WORKDIR/opengnsys/admin/$SWAGGERFILE -d $INSTALL_TARGET/www/rest
+
+ # Compatibilidad con dispositivos móviles.
+ COMPATDIR="$INSTALL_TARGET/www/principal"
+ for f in acciones administracion aula aulas hardwares imagenes menus repositorios softwares; do
+ sed 's/clickcontextualnodo/clicksupnodo/g' $COMPATDIR/$f.php > $COMPATDIR/$f.device.php
+ done
+ cp -a $COMPATDIR/imagenes.device.php $COMPATDIR/imagenes.device4.php
+ # Acceso al manual de usuario
+ ln -fs ../doc/userManual $INSTALL_TARGET/www/userManual
+ # Ficheros de log de la API REST.
+ touch $INSTALL_TARGET/log/{ogagent,remotepc,rest}.log
-echoAndLog "${FUNCNAME}(): Web files installed successfully."
+ echoAndLog "${FUNCNAME}(): Web files installed successfully."
}
# Copiar ficheros en la zona de descargas de OpenGnsys Web Console.
@@ -1236,8 +1203,7 @@ function createDirs()
mkdir -p $path_opengnsys_base/log/clients
ln -fs $path_opengnsys_base/log /var/log/opengnsys
mkdir -p $path_opengnsys_base/sbin
- mkdir -p $path_opengnsys_base/www/descargas
- mkdir -p $path_opengnsys_base/www3 ### TEMPORAL
+ mkdir -p $path_opengnsys_base/www
mkdir -p $path_opengnsys_base/images/groups
mkdir -p $TFTPCFGDIR
ln -fs $TFTPCFGDIR $path_opengnsys_base/tftpboot
@@ -1331,6 +1297,45 @@ function copyServerFiles ()
popd
}
+####################################################################
+### Funciones de compilación de código fuente de servicios
+####################################################################
+
+# Compilar los servicios de OpenGnsys
+function servicesCompilation ()
+{
+ local hayErrores=0
+
+ # Compilar OpenGnsys Server
+ echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Server"
+ pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
+ make && mv ogAdmServer $INSTALL_TARGET/sbin
+ if [ $? -ne 0 ]; then
+ echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Server"
+ hayErrores=1
+ fi
+ popd
+ # Compilar OpenGnsys Agent
+ echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Agent"
+ pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
+ make && mv ogAdmAgent $INSTALL_TARGET/sbin
+ if [ $? -ne 0 ]; then
+ echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Agent"
+ hayErrores=1
+ fi
+ popd
+ # Compilar OpenGnsys Client
+ echoAndLog "${FUNCNAME}(): Compiling OpenGnsys Admin Client"
+ pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
+ make && mv ogAdmClient ../../../../client/shared/bin
+ if [ $? -ne 0 ]; then
+ echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Client"
+ hayErrores=1
+ fi
+ popd
+
+ return $hayErrores
+}
####################################################################
### Funciones de copia de la Interface de administración
@@ -1422,23 +1427,6 @@ function clientCreate()
}
-# Función temporal para generar y copiar el agente OGAgent para ogLive
-function createOgagentPackage ()
-{
-local ogagentdir=$WORKDIR/opengnsys/admin/Sources/Clients/ogagent/oglive
-
-echoAndLog "${FUNCNAME}(): Creating OGAgent for ogLive package..."
-OGAGENTFILE=$($ogagentdir/build-package.sh | awk -F\' '/building package/ {print $(NF-1)}')
-if [ -z "$OGAGENTFILE" ]; then
- errorAndLog "${FUNCNAME}(): Error generating OGAgent pacakage."
- return 1
-fi
-OGAGENTFILE=$(realpath $ogagentdir/$OGAGENTFILE)
-cp -va $OGAGENTFILE $INSTALL_TARGET/images
-echoAndLog "${FUNCNAME}(): OGAgent for ogLive package has been copied to the repository"
-}
-
-
# Configuración básica de servicios de OpenGnsys
function openGnsysConfigure()
{
@@ -1472,15 +1460,43 @@ function openGnsysConfigure()
for dev in ${DEVICE[*]}; do
if [ -n "${SERVERIP[i]}" ]; then
sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
+ -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
+ -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
+ -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
+ $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer/ogAdmServer.cfg > $INSTALL_TARGET/etc/ogAdmServer-$dev.cfg
+ sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
-e "s/REPOKEY/$OPENGNSYS_REPOKEY/g" \
$WORKDIR/opengnsys/repoman/etc/ogAdmRepo.cfg.tmpl > $INSTALL_TARGET/etc/ogAdmRepo-$dev.cfg
+ sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
+ -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
+ -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
+ -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
+ $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent/ogAdmAgent.cfg > $INSTALL_TARGET/etc/ogAdmAgent-$dev.cfg
+ CONSOLEURL="https://${SERVERIP[i]}/opengnsys"
+ sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
+ -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
+ -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
+ -e "s/DATABASE/$OPENGNSYS_DATABASE/g" \
+ -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
+ $INSTALL_TARGET/www/controlacceso.php > $INSTALL_TARGET/www/controlacceso-$dev.php
+ sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
+ -e "s/OPENGNSYSURL/${CONSOLEURL//\//\\/}/g" \
+ $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient/ogAdmClient.cfg > $INSTALL_TARGET/client/etc/ogAdmClient-$dev.cfg
if [ "$dev" == "$DEFAULTDEV" ]; then
OPENGNSYS_CONSOLEURL="$CONSOLEURL"
fi
fi
let i++
done
+ ln -f $INSTALL_TARGET/etc/ogAdmServer-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmServer.cfg
ln -f $INSTALL_TARGET/etc/ogAdmRepo-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmRepo.cfg
+ ln -f $INSTALL_TARGET/etc/ogAdmAgent-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmAgent.cfg
+ ln -f $INSTALL_TARGET/client/etc/ogAdmClient-$DEFAULTDEV.cfg $INSTALL_TARGET/client/etc/ogAdmClient.cfg
+ ln -f $INSTALL_TARGET/www/controlacceso-$DEFAULTDEV.php $INSTALL_TARGET/www/controlacceso.php
+ chown root:root $INSTALL_TARGET/etc/{ogAdmServer,ogAdmAgent}*.cfg
+ chmod 600 $INSTALL_TARGET/etc/{ogAdmServer,ogAdmAgent}*.cfg
+ chown $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/www/controlacceso*.php
+ chmod 600 $INSTALL_TARGET/www/controlacceso*.php
# Configuración del motor de clonación.
# - Zona horaria del servidor.
@@ -1501,6 +1517,10 @@ EOT
service=$MYSQLSERV
$DISABLESERVICE
fi
+
+ echoAndLog "${FUNCNAME}(): Starting OpenGnsys services."
+ service="opengnsys"
+ $ENABLESERVICE; $STARTSERVICE
}
@@ -1627,6 +1647,13 @@ else
ln -fs "$(dirname $PROGRAMDIR)" opengnsys
fi
+# Compilar código fuente de los servicios de OpenGnsys.
+servicesCompilation
+if [ $? -ne 0 ]; then
+ errorAndLog "Error while compiling OpenGnsys services"
+ exit 1
+fi
+
# Copiar carpeta Interface entre administración y motor de clonación.
copyInterfaceAdm
if [ $? -ne 0 ]; then
@@ -1708,6 +1735,28 @@ if [ $? -ne 0 ]; then
fi
fi
+
+mysqlCheckDbIsEmpty ${OPENGNSYS_DATABASE}
+if [ $? -eq 0 ]; then
+ echoAndLog "Creating tables..."
+ if [ -f $WORKDIR/$OPENGNSYS_DB_CREATION_FILE ]; then
+ mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_CREATION_FILE
+ else
+ errorAndLog "Unable to locate $WORKDIR/$OPENGNSYS_DB_CREATION_FILE!!"
+ exit 1
+ fi
+else
+ # Si existe fichero ogBDAdmin-VersLocal-VersRepo.sql; aplicar cambios.
+ REPOVERSION=$(jq -r '.version' $WORKDIR/opengnsys/doc/VERSION.json)
+ OPENGNSYS_DB_UPDATE_FILE="opengnsys/admin/Database/$OPENGNSYS_DATABASE-$INSTVERSION-$REPOVERSION.sql"
+ if [ -f $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE ]; then
+ echoAndLog "Updating tables from version $INSTVERSION to $REPOVERSION"
+ mysqlImportSqlFileToDb ${OPENGNSYS_DATABASE} $WORKDIR/$OPENGNSYS_DB_UPDATE_FILE
+ else
+ echoAndLog "Database unchanged."
+ fi
+fi
+# Eliminar fichero temporal con credenciales de acceso a MySQL.
rm -f $TMPMYCNF
# Copiando páqinas web.
@@ -1740,9 +1789,6 @@ for i in $OGLIVE; do
fi
done
-# Copiar paquete ogagent-oglive en el repositorio.
-createOgagentPackage
-
# Configuración de servicios de OpenGnsys
openGnsysConfigure
diff --git a/installer/opengnsys_installer3.sh b/installer/opengnsys_installer3.sh
new file mode 100755
index 00000000..7ebc18f6
--- /dev/null
+++ b/installer/opengnsys_installer3.sh
@@ -0,0 +1,1757 @@
+#!/bin/bash
+
+#####################################################################
+####### Script instalador OpenGnsys
+####### Autor: Luis Guillén <lguillen@unizar.es>
+#####################################################################
+
+
+#### AVISO: Puede editar configuración de acceso por defecto.
+#### WARNING: Edit default access configuration if you wish.
+DEFAULT_MYSQL_ROOT_PASSWORD="passwordroot" # Clave por defecto root de MySQL
+DEFAULT_OPENGNSYS_DB_USER="admin" # Usuario por defecto de acceso a la base de datos
+DEFAULT_OPENGNSYS_DB_PASSWD="admin" # Clave por defecto de acceso a la base de datos
+DEFAULT_OPENGNSYS_CLIENT_PASSWD="og" # Clave por defecto de acceso del cliente
+
+# Sólo ejecutable por usuario root
+if [ "$(whoami)" != 'root' ]; then
+ echo "ERROR: this program must run under root privileges!!"
+ exit 1
+fi
+
+echo -e "\\nOpenGnsys Installation"
+echo "=============================="
+
+# Clave root de MySQL
+while : ; do
+ echo -n -e "\\nEnter root password for MySQL (${DEFAULT_MYSQL_ROOT_PASSWORD}): ";
+ read -r MYSQL_ROOT_PASSWORD
+ if [ -n "${MYSQL_ROOT_PASSWORD//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico
+ echo -e "\\aERROR: Must be alphanumeric, try again..."
+ else
+ # Si esta vacio ponemos el valor por defecto
+ MYSQL_ROOT_PASSWORD="${MYSQL_ROOT_PASSWORD:-$DEFAULT_MYSQL_ROOT_PASSWORD}"
+ break
+ fi
+done
+
+# Usuario de acceso a la base de datos
+while : ; do
+ echo -n -e "\\nEnter username for OpenGnsys console (${DEFAULT_OPENGNSYS_DB_USER}): "
+ read -r OPENGNSYS_DB_USER
+ if [ -n "${OPENGNSYS_DB_USER//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico
+ echo -e "\\aERROR: Must be alphanumeric, try again..."
+ else
+ # Si esta vacio ponemos el valor por defecto
+ OPENGNSYS_DB_USER="${OPENGNSYS_DB_USER:-$DEFAULT_OPENGNSYS_DB_USER}"
+ break
+ fi
+done
+
+# Clave de acceso a la base de datos
+while : ; do
+ echo -n -e "\\nEnter password for OpenGnsys console (${DEFAULT_OPENGNSYS_DB_PASSWD}): "
+ read -r OPENGNSYS_DB_PASSWD
+ if [ -n "${OPENGNSYS_DB_PASSWD//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico
+ echo -e "\\aERROR: Must be alphanumeric, try again..."
+ else
+ # Si esta vacio ponemos el valor por defecto
+ OPENGNSYS_DB_PASSWD="${OPENGNSYS_DB_PASSWD:-$DEFAULT_OPENGNSYS_DB_PASSWD}"
+ break
+ fi
+done
+
+# Clave de acceso del cliente
+while : ; do
+ echo -n -e "\\nEnter root password for OpenGnsys client (${DEFAULT_OPENGNSYS_CLIENT_PASSWD}): "
+ read -r OPENGNSYS_CLIENT_PASSWD
+ if [ -n "${OPENGNSYS_CLIENT_PASSWD//[a-zA-Z0-9]/}" ]; then # Comprobamos que sea un valor alfanumerico
+ echo -e "\\aERROR: Must be alphanumeric, try again..."
+ else
+ # Si esta vacio ponemos el valor por defecto
+ OPENGNSYS_CLIENT_PASSWD="${OPENGNSYS_CLIENT_PASSWD:-$DEFAULT_OPENGNSYS_CLIENT_PASSWD}"
+ break
+ fi
+done
+
+# Selección de clientes ogLive para descargar.
+while : ; do
+ echo -e "\\nChoose ogLive client to install."
+ echo -e "1) Kernel 4.13, 64-bit, EFI-compatible"
+ echo -e "2) Kernel 3.2, 32-bit"
+ echo -e "3) Both"
+ echo -n -e "Please, type a valid number (1): "
+ read -r OPT
+ case "$OPT" in
+ 1|"") OGLIVE="ogLive-xenial-4.13.0-17-generic-amd64-r5520.iso"
+ break ;;
+ 2) OGLIVE="ogLive-precise-3.2.0-23-generic-r5159.iso"
+ break ;;
+ 3) OGLIVE="ogLive-xenial-4.13.0-17-generic-amd64-r5520.iso ogLive-precise-3.2.0-23-generic-r5159.iso";
+ break ;;
+ *) echo -e "\\aERROR: unknown option, try again."
+ esac
+done
+
+echo -e "\\n=============================="
+
+# Comprobar si se ha descargado el paquete comprimido (REMOTE=0) o sólo el instalador (REMOTE=1).
+PROGRAMDIR=$(readlink -e "$(dirname "$0")")
+PROGRAMNAME=$(basename "$0")
+OPENGNSYS_SERVER="opengnsys.es"
+DOWNLOADURL="https://$OPENGNSYS_SERVER/trac/downloads"
+if [ -d "$PROGRAMDIR/../installer" ]; then
+ REMOTE=0
+else
+ REMOTE=1
+fi
+BRANCH="devel"
+CODE_URL="https://codeload.github.com/opengnsys/OpenGnsys/zip/$BRANCH"
+API_URL="https://api.github.com/repos/opengnsys/OpenGnsys/branches/$BRANCH"
+
+WORKDIR=/tmp/opengnsys_installer
+mkdir -p $WORKDIR
+
+# Directorio destino de OpenGnsys.
+INSTALL_TARGET=/opt/opengnsys
+PATH=$PATH:$INSTALL_TARGET/bin
+
+# Registro de incidencias.
+OGLOGFILE=$INSTALL_TARGET/log/${PROGRAMNAME%.sh}.log
+LOG_FILE=/tmp/$(basename $OGLOGFILE)
+
+# Usuario del cliente para acceso remoto.
+OPENGNSYS_CLIENT_USER="opengnsys"
+
+# Nombre de la base datos.
+OPENGNSYS_DATABASE="opengnsys"
+
+
+#####################################################################
+####### Funciones de configuración
+#####################################################################
+
+# Generar variables de configuración del instalador
+# Variables globales:
+# - OSDISTRIB, OSVERSION - tipo y versión de la distribución GNU/Linux
+# - PREREQS, DEPENDENCIES - arrays de prerrequisitos y dependencias que deben estar instaladas
+# - UPDATEPKGLIST, INSTALLPKGS, CHECKPKGS - comandos para gestión de paquetes
+# - INSTALLEXTRADEPS - instalar dependencias no incluidas en la distribución
+# - STARTSERVICE, ENABLESERVICE - iniciar y habilitar un servicio
+# - STOPSERVICE, DISABLESERVICE - parar y deshabilitar un servicio
+# - APACHESERV, APACHECFGDIR, APACHESITESDIR, APACHEUSER, APACHEGROUP - servicio y configuración de Apache
+# - APACHEENABLEMODS, APACHEENABLESSL, APACHEMAKECERT - habilitar módulos y certificado SSL
+# - APACHEENABLEOG, APACHEOGSITE, - habilitar sitio web de OpenGnsys
+# - PHPFPMSERV - servicio PHP FastCGI Process Manager para Apache
+# - INETDSERV - servicio Inetd
+# - DHCPSERV, DHCPCFGDIR - servicio y configuración de DHCP
+# - MYSQLSERV, TMPMYCNF - servicio MySQL y fichero temporal con credenciales de acceso
+# - MARIADBSERV - servicio MariaDB (sustituto de MySQL en algunas distribuciones)
+# - RSYNCSERV, RSYNCCFGDIR - servicio y configuración de Rsync
+# - SAMBASERV, SAMBACFGDIR - servicio y configuración de Samba
+# - TFTPSERV, TFTPCFGDIR - servicio y configuración de TFTP/PXE
+function autoConfigure()
+{
+# Detectar sistema operativo del servidor (compatible con fichero os-release y con LSB).
+if [ -f /etc/os-release ]; then
+ source /etc/os-release
+ OSDISTRIB="$ID"
+ OSVERSION="$VERSION_ID"
+else
+ OSDISTRIB=$(lsb_release -is 2>/dev/null)
+ OSVERSION=$(lsb_release -rs 2>/dev/null)
+fi
+# Convertir distribución a minúsculas y obtener solo el 1er número de versión.
+OSDISTRIB="${OSDISTRIB,,}"
+OSVERSION="${OSVERSION%%.*}"
+
+# Configuración según la distribución GNU/Linux (usar minúsculas).
+case "$OSDISTRIB" in
+ ubuntu|debian|linuxmint)
+ PREREQS=( curl software-properties-common )
+ DEPENDENCIES=( subversion apache2 php php-ldap php-fpm mysql-server php-mysql isc-dhcp-server bittorrent tftp-hpa tftpd-hpa xinetd build-essential g++-multilib libmysqlclient-dev wget doxygen graphviz bittornado ctorrent samba rsync unzip netpipes debootstrap schroot squashfs-tools btrfs-tools procps arp-scan realpath php-curl gettext moreutils jq udpcast libev-dev shim-signed grub-efi-amd64-signed git php-mbstring php-xml nodejs debhelper )
+ UPDATEPKGLIST="apt-get update"
+ INSTALLPKG="apt-get -y install"
+ CHECKPKG="dpkg -s \$package 2>/dev/null | grep Status | grep -qw install"
+ if which service &>/dev/null; then
+ STARTSERVICE="eval service \$service restart"
+ STOPSERVICE="eval service \$service stop"
+ else
+ STARTSERVICE="eval /etc/init.d/\$service restart"
+ STOPSERVICE="eval /etc/init.d/\$service stop"
+ fi
+ ENABLESERVICE="eval update-rc.d \$service defaults"
+ DISABLESERVICE="eval update-rc.d \$service disable"
+ APACHESERV=apache2
+ APACHECFGDIR=/etc/apache2
+ APACHESITESDIR=sites-available
+ APACHEOGSITE=opengnsys
+ APACHEUSER="www-data"
+ APACHEGROUP="www-data"
+ APACHEENABLEMODS="a2enmod ssl rewrite proxy_fcgi actions alias"
+ APACHEENABLESSL="a2ensite default-ssl"
+ APACHEENABLEOG="a2ensite $APACHEOGSITE"
+ APACHEMAKECERT="make-ssl-cert generate-default-snakeoil --force-overwrite"
+ DHCPSERV=isc-dhcp-server
+ DHCPCFGDIR=/etc/dhcp
+ INETDSERV=xinetd
+ INETDCFGDIR=/etc/xinetd.d
+ MYSQLSERV=mysql
+ MARIADBSERV=mariadb
+ PHPFPMSERV=php-fpm
+ RSYNCSERV=rsync
+ RSYNCCFGDIR=/etc
+ SAMBASERV=smbd
+ SAMBACFGDIR=/etc/samba
+ TFTPCFGDIR=/var/lib/tftpboot
+ ;;
+ fedora|centos)
+ PREREQS=( curl )
+ DEPENDENCIES=( subversion httpd mod_ssl php-ldap php-fpm 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 doxygen graphviz ctorrent samba samba-client rsync unzip debootstrap schroot squashfs-tools python-crypto arp-scan procps-ng gettext moreutils jq net-tools udpcast libev-devel shim-x64 grub2-efi-x64 grub2-efi-x64-modules http://ftp.altlinux.org/pub/distributions/ALTLinux/5.1/branch/$(arch)/RPMS.classic/netpipes-4.2-alt1.$(arch).rpm )
+ [ "$OSDISTRIB" == "centos" ] && UPDATEPKGLIST="yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-$OSVERSION.noarch.rpm http://rpms.remirepo.net/enterprise/remi-release-$OSVERSION.rpm"
+ INSTALLEXTRADEPS=( 'pushd /tmp; wget -t3 http://ftp.acc.umu.se/mirror/bittornado/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' )
+ INSTALLPKG="yum install -y libstdc++ libstdc++.i686"
+ CHECKPKG="rpm -q --quiet \$package"
+ SYSTEMD=$(which systemctl 2>/dev/null)
+ if [ -n "$SYSTEMD" ]; then
+ STARTSERVICE="eval systemctl start \$service.service"
+ STOPSERVICE="eval systemctl stop \$service.service"
+ ENABLESERVICE="eval systemctl enable \$service.service"
+ DISABLESERVICE="eval systemctl disable \$service.service"
+ else
+ STARTSERVICE="eval service \$service start"
+ STOPSERVICE="eval service \$service stop"
+ ENABLESERVICE="eval chkconfig \$service on"
+ DISABLESERVICE="eval chkconfig \$service off"
+ fi
+ APACHESERV=httpd
+ APACHECFGDIR=/etc/httpd/conf.d
+ APACHEOGSITE=opengnsys.conf
+ APACHEUSER="apache"
+ APACHEGROUP="apache"
+ APACHEREWRITEMOD="sed -i '/rewrite/s/^#//' $APACHECFGDIR/../*.conf"
+ DHCPSERV=dhcpd
+ DHCPCFGDIR=/etc/dhcp
+ INETDSERV=xinetd
+ INETDCFGDIR=/etc/xinetd.d
+ MYSQLSERV=mysqld
+ MARIADBSERV=mariadb
+ PHPFPMSERV=php-fpm
+ RSYNCSERV=rsync
+ RSYNCCFGDIR=/etc
+ SAMBASERV=smb
+ SAMBACFGDIR=/etc/samba
+ TFTPSERV=tftp
+ TFTPCFGDIR=/var/lib/tftpboot
+ ;;
+ "") echo "ERROR: Unknown Linux distribution, please install \"lsb_release\" command."
+ exit 1 ;;
+ *) echo "ERROR: Distribution not supported by OpenGnsys."
+ exit 1 ;;
+esac
+# Instalar Composer y Angular-CLI.
+INSTALLEXTRADEPS=( ${INSTALLEXTRADEPS[@]} \
+ 'if [ ! -f /usr/local/bin/composer.phar ]; then php -r "copy(\"https://getcomposer.org/installer\", \"/tmp/composer-setup.php\");"; php /tmp/composer-setup.php --install-dir=/usr/local/bin; rm -f /tmp/composer-setup.php; else /usr/local/bin/composer.phar self-update; fi' \
+ 'npm install -g @angular/cli@6.2.3' )
+
+# Fichero de credenciales de acceso a MySQL.
+TMPMYCNF=/tmp/.my.cnf.$$
+}
+
+
+# Modificar variables de configuración tras instalar paquetes del sistema.
+function autoConfigurePost()
+{
+# Configuraciones específicas para Samba y TFTP en Debian 6.
+[ -z "$SYSTEMD" -a ! -e /etc/init.d/$SAMBASERV ] && SAMBASERV=samba
+[ ! -e $TFTPCFGDIR ] && TFTPCFGDIR=/srv/tftp
+}
+
+
+# Cargar lista de paquetes del sistema y actualizar algunas variables de configuración
+# dependiendo de la versión instalada.
+function updatePackageList()
+{
+local DHCPVERSION PHP7VERSION
+
+# Si es necesario, actualizar la lista de paquetes disponibles e instalar prerrequisitos.
+[ -n "$UPDATEPKGLIST" ] && eval $UPDATEPKGLIST
+[ ${#PREREQS[@]} -gt 0 ] && eval $INSTALLPKG ${PREREQS[@]}
+
+# Configuración personallizada de algunos paquetes.
+case "$OSDISTRIB" in
+ ubuntu|linuxmint) # Postconfiguación personalizada para Ubuntu.
+ # Instalar prerrequisitos.
+ # Configuración para DHCP v3.
+ DHCPVERSION=$(apt-cache show $(apt-cache pkgnames|egrep "dhcp.?-server$") | \
+ awk '/Version/ {print substr($2,1,1);}' | \
+ sort -n | tail -1)
+ if [ $DHCPVERSION = 3 ]; then
+ DEPENDENCIES=( ${DEPENDENCIES[@]/isc-dhcp-server/dhcp3-server} )
+ DHCPSERV=dhcp3-server
+ DHCPCFGDIR=/etc/dhcp3
+ fi
+ # Configuración para PHP 7 en Ubuntu.
+ if [ -z "$(apt-cache pkgnames php7)" ]; then
+ add-apt-repository -y ppa:ondrej/php
+ eval $UPDATEPKGLIST
+ PHP7VERSION=$(apt-cache pkgnames php7. | sort | tail -1)
+ PHPFPMSERV="${PHP7VERSION}-fpm"
+ DEPENDENCIES=( ${DEPENDENCIES[@]//php/$PHP7VERSION} )
+ fi
+ # Adaptar dependencias para libmysqlclient.
+ [ -z "$(apt-cache pkgnames libmysqlclient-dev)" ] && [ -n "$(apt-cache pkgnames libmysqlclient15)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//libmysqlclient-dev/libmysqlclient15} )
+ # Paquete correcto para realpath.
+ [ -z "$(apt-cache pkgnames realpath)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//realpath/coreutils} )
+ # Instalar NodeJS.
+ curl -sL https://deb.nodesource.com/setup_10.x | bash -
+ ;;
+ centos) # Postconfiguación personalizada para CentOS.
+ # Configuración para PHP 7.
+ PHP7VERSION=$(yum list -q php7\* 2>/dev/null | awk -F. '/^php/ {print $1; exit;}')
+ PHPFPMSERV="${PHP7VERSION}-${PHPFPMSERV}"
+ DEPENDENCIES=( ${PHP7VERSION} ${DEPENDENCIES[@]//php/$PHP7VERSION-php} )
+ # Cambios a aplicar a partir de CentOS 7.
+ if [ $OSVERSION -ge 7 ]; then
+ # Sustituir MySQL por MariaDB.
+ DEPENDENCIES=( ${DEPENDENCIES[*]/mysql-/mariadb-} )
+ # Instalar ctorrent de EPEL para CentOS 6 (no disponible en CentOS 7).
+ DEPENDENCIES=( ${DEPENDENCIES[*]/ctorrent/http://dl.fedoraproject.org/pub/epel/6/$(arch)/Packages/c/ctorrent-1.3.4-14.dnh3.3.2.el6.$(arch).rpm} )
+ fi
+ # Instalar NodeJS.
+ curl -sL https://rpm.nodesource.com/setup_10.x | bash -
+ ;;
+ fedora) # Postconfiguación personalizada para Fedora.
+ # Incluir paquetes específicos.
+ DEPENDENCIES=( ${DEPENDENCIES[@]} btrfs-progs )
+ # Sustituir MySQL por MariaDB a partir de Fedora 20.
+ [ $OSVERSION -ge 20 ] && DEPENDENCIES=( ${DEPENDENCIES[*]/mysql-/mariadb-} )
+ # Instalar NodeJS.
+ curl -sL https://rpm.nodesource.com/setup_10.x | bash -
+ ;;
+esac
+}
+
+
+#####################################################################
+####### Algunas funciones útiles de propósito general:
+#####################################################################
+
+function getDateTime()
+{
+ date "+%Y%m%d-%H%M%S"
+}
+
+# Escribe a fichero y muestra por pantalla
+function echoAndLog()
+{
+ local DATETIME=`getDateTime`
+ echo "$1"
+ echo "$DATETIME;$SSH_CLIENT;$1" >> $LOG_FILE
+}
+
+# Escribe a fichero y muestra mensaje de error
+function errorAndLog()
+{
+ local DATETIME=`getDateTime`
+ echo "ERROR: $1"
+ echo "$DATETIME;$SSH_CLIENT;ERROR: $1" >> $LOG_FILE
+}
+
+# Escribe a fichero y muestra mensaje de aviso
+function warningAndLog()
+{
+ local DATETIME=`getDateTime`
+ echo "Warning: $1"
+ echo "$DATETIME;$SSH_CLIENT;Warning: $1" >> $LOG_FILE
+}
+
+# Comprueba si el elemento pasado en $2 está en el array $1
+function isInArray()
+{
+ if [ $# -ne 2 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local deps
+ local is_in_array=1
+ local element="$2"
+
+ echoAndLog "${FUNCNAME}(): checking if $2 is in $1"
+ eval "deps=( \"\${$1[@]}\" )"
+
+ # Copia local del array del parámetro 1.
+ for (( i = 0 ; i < ${#deps[@]} ; i++ )); do
+ if [ "${deps[$i]}" = "${element}" ]; then
+ echoAndLog "isInArray(): $element found in array"
+ is_in_array=0
+ fi
+ done
+
+ if [ $is_in_array -ne 0 ]; then
+ echoAndLog "${FUNCNAME}(): $element NOT found in array"
+ fi
+
+ return $is_in_array
+}
+
+
+#####################################################################
+####### Funciones de manejo de paquetes Debian
+#####################################################################
+
+function checkPackage()
+{
+ package=$1
+ if [ -z $package ]; then
+ errorAndLog "${FUNCNAME}(): parameter required"
+ exit 1
+ fi
+ echoAndLog "${FUNCNAME}(): checking if package $package exists"
+ eval $CHECKPKG
+ if [ $? -eq 0 ]; then
+ echoAndLog "${FUNCNAME}(): package $package exists"
+ return 0
+ else
+ echoAndLog "${FUNCNAME}(): package $package doesn't exists"
+ return 1
+ fi
+}
+
+# Recibe array con dependencias
+# por referencia deja un array con las dependencias no resueltas
+# devuelve 1 si hay alguna dependencia no resuelta
+function checkDependencies()
+{
+ if [ $# -ne 2 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ echoAndLog "${FUNCNAME}(): checking dependences"
+ uncompletedeps=0
+
+ # copia local del array del parametro 1
+ local deps
+ eval "deps=( \"\${$1[@]}\" )"
+
+ declare -a local_notinstalled
+
+ for (( i = 0 ; i < ${#deps[@]} ; i++ ))
+ do
+ checkPackage ${deps[$i]}
+ if [ $? -ne 0 ]; then
+ local_notinstalled[$uncompletedeps]=$package
+ let uncompletedeps=uncompletedeps+1
+ fi
+ done
+
+ # relleno el array especificado en $2 por referencia
+ for (( i = 0 ; i < ${#local_notinstalled[@]} ; i++ ))
+ do
+ eval "${2}[$i]=${local_notinstalled[$i]}"
+ done
+
+ # retorna el numero de paquetes no resueltos
+ echoAndLog "${FUNCNAME}(): dependencies uncompleted: $uncompletedeps"
+ return $uncompletedeps
+}
+
+# Recibe un array con las dependencias y lo instala
+function installDependencies()
+{
+ if [ $# -ne 1 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+ echoAndLog "${FUNCNAME}(): installing uncompleted dependencies"
+
+ # copia local del array del parametro 1
+ local deps
+ eval "deps=( \"\${$1[@]}\" )"
+
+ local string_deps=""
+ for (( i = 0 ; i < ${#deps[@]} ; i++ ))
+ do
+ string_deps="$string_deps ${deps[$i]}"
+ done
+
+ if [ -z "${string_deps}" ]; then
+ errorAndLog "${FUNCNAME}(): array of dependeces is empty"
+ exit 1
+ fi
+
+ OLD_DEBIAN_FRONTEND=$DEBIAN_FRONTEND # Debian/Ubuntu
+ export DEBIAN_FRONTEND=noninteractive
+
+ echoAndLog "${FUNCNAME}(): now $string_deps will be installed"
+ eval $INSTALLPKG $string_deps
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error installing dependencies"
+ return 1
+ fi
+
+ DEBIAN_FRONTEND=$OLD_DEBIAN_FRONTEND # Debian/Ubuntu
+ 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
+
+ echoAndLog "${FUNCNAME}(): dependencies installed"
+}
+
+# Hace un backup del fichero pasado por parámetro
+# deja un -last y uno para el día
+function backupFile()
+{
+ if [ $# -ne 1 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local file="$1"
+ local dateymd=`date +%Y%m%d`
+
+ if [ ! -f "$file" ]; then
+ warningAndLog "${FUNCNAME}(): file $file doesn't exists"
+ return 1
+ fi
+
+ echoAndLog "${FUNCNAME}(): making $file backup"
+
+ # realiza una copia de la última configuración como last
+ cp -a "$file" "${file}-LAST"
+
+ # si para el día no hay backup lo hace, sino no
+ if [ ! -f "${file}-${dateymd}" ]; then
+ cp -a "$file" "${file}-${dateymd}"
+ fi
+
+ echoAndLog "${FUNCNAME}(): $file backup success"
+}
+
+#####################################################################
+####### Funciones para el manejo de bases de datos
+#####################################################################
+
+# This function set password to root
+function mysqlSetRootPassword()
+{
+ if [ $# -ne 1 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local root_mysql="$1"
+ echoAndLog "${FUNCNAME}(): setting root password in MySQL server"
+ mysqladmin -u root password "$root_mysql"
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error while setting root password in MySQL server"
+ return 1
+ fi
+ echoAndLog "${FUNCNAME}(): root password saved!"
+ return 0
+}
+
+# Si el servicio mysql esta ya instalado cambia la variable de la clave del root por la ya existente
+function mysqlGetRootPassword()
+{
+ local pass_mysql
+ local pass_mysql2
+ # Comprobar si MySQL está instalado con la clave de root por defecto.
+ if mysql -u root -p"$MYSQL_ROOT_PASSWORD" <<<"quit" 2>/dev/null; then
+ echoAndLog "${FUNCNAME}(): Using default mysql root password."
+ else
+ stty -echo
+ echo "There is a MySQL service already installed."
+ read -p "Enter MySQL root password: " pass_mysql
+ echo ""
+ read -p "Confrim password:" pass_mysql2
+ echo ""
+ stty echo
+ if [ "$pass_mysql" == "$pass_mysql2" ] ;then
+ MYSQL_ROOT_PASSWORD="$pass_mysql"
+ return 0
+ else
+ echo "The keys don't match. Do not configure the server's key,"
+ echo "transactions in the database will give error."
+ return 1
+ fi
+ fi
+}
+
+# comprueba si puede conectar con mysql con el usuario root
+function mysqlTestConnection()
+{
+ if [ $# -ne 1 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local root_password="$1"
+ echoAndLog "${FUNCNAME}(): checking connection to mysql..."
+ # Componer fichero con credenciales de conexión a MySQL.
+ touch $TMPMYCNF
+ chmod 600 $TMPMYCNF
+ cat << EOT > $TMPMYCNF
+[client]
+user=root
+password=$root_password
+EOT
+ # Borrar el fichero temporal si termina el proceso de instalación.
+ trap "rm -f $TMPMYCNF" 0 1 2 3 6 9 15
+ # Comprobar conexión a MySQL.
+ echo "" | mysql --defaults-extra-file=$TMPMYCNF
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): connection to mysql failed, check root password and if daemon is running!"
+ return 1
+ else
+ echoAndLog "${FUNCNAME}(): connection success"
+ return 0
+ fi
+}
+
+# comprueba si la base de datos existe
+function mysqlDbExists()
+{
+ if [ $# -ne 1 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local database="$1"
+ echoAndLog "${FUNCNAME}(): checking if $database exists..."
+ echo "show databases" | mysql --defaults-extra-file=$TMPMYCNF | grep "^${database}$"
+ if [ $? -ne 0 ]; then
+ echoAndLog "${FUNCNAME}():database $database doesn't exists"
+ return 1
+ else
+ echoAndLog "${FUNCNAME}():database $database exists"
+ return 0
+ fi
+}
+
+# Comprueba si la base de datos está vacía.
+function mysqlCheckDbIsEmpty()
+{
+ if [ $# -ne 1 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local database="$1"
+ echoAndLog "${FUNCNAME}(): checking if $database is empty..."
+ num_tablas=`echo "show tables" | mysql --defaults-extra-file=$TMPMYCNF "${database}" | wc -l`
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error executing query, check database and root password"
+ exit 1
+ fi
+
+ if [ $num_tablas -eq 0 ]; then
+ echoAndLog "${FUNCNAME}():database $database is empty"
+ return 0
+ else
+ echoAndLog "${FUNCNAME}():database $database has tables"
+ return 1
+ fi
+
+}
+
+# Importa un fichero SQL en la base de datos.
+# Parámetros:
+# - 1: nombre de la BD.
+# - 2: fichero a importar.
+# Nota: el fichero SQL puede contener las siguientes palabras reservadas:
+# - SERVERIP: se sustituye por la dirección IP del servidor.
+# - DBUSER: se sustituye por usuario de conexión a la BD definido en este script.
+# - DBPASSWD: se sustituye por la clave de conexión a la BD definida en este script.
+function mysqlImportSqlFileToDb()
+{
+ if [ $# -ne 2 ]; then
+ errorAndLog "${FNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local database="$1"
+ local sqlfile="$2"
+ local tmpfile=$(mktemp)
+ local i=0
+ local dev=""
+ local status
+ # Claves aleatorias para acceso a las APIs REST.
+ local OPENGNSYS_APIKEY=$(php -r 'echo md5(uniqid(rand(), true));')
+ OPENGNSYS_REPOKEY=$(php -r 'echo md5(uniqid(rand(), true));')
+
+ if [ ! -f $sqlfile ]; then
+ errorAndLog "${FUNCNAME}(): Unable to locate $sqlfile!!"
+ return 1
+ fi
+
+ echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..."
+ chmod 600 $tmpfile
+ for dev in ${DEVICE[*]}; do
+ if [ "${DEVICE[i]}" == "$DEFAULTDEV" ]; then
+ sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
+ -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
+ -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
+ -e "s/APIKEY/$OPENGNSYS_APIKEY/g" \
+ -e "s/REPOKEY/$OPENGNSYS_REPOKEY/g" \
+ $sqlfile > $tmpfile
+ fi
+ let i++
+ done
+ mysql --defaults-extra-file=$TMPMYCNF --default-character-set=utf8 "${database}" < $tmpfile
+ status=$?
+ rm -f $tmpfile
+ if [ $status -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error while importing $sqlfile in database $database"
+ return 1
+ fi
+ echoAndLog "${FUNCNAME}(): file imported to database $database"
+ return 0
+}
+
+# Crea la base de datos
+function mysqlCreateDb()
+{
+ if [ $# -ne 1 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local database="$1"
+
+ echoAndLog "${FUNCNAME}(): creating database..."
+ mysqladmin --defaults-extra-file=$TMPMYCNF create $database
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error while creating database $database"
+ return 1
+ fi
+ # Quitar modo ONLY_FULL_GROUP_BY de MySQL (ticket #730).
+ mysql --defaults-extra-file=$TMPMYCNF -e "SET GLOBAL sql_mode=(SELECT TRIM(BOTH ',' FROM REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')));"
+
+ echoAndLog "${FUNCNAME}(): database $database created"
+ return 0
+}
+
+# Comprueba si ya está definido el usuario de acceso a la BD.
+function mysqlCheckUserExists()
+{
+if [ $# -ne 1 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+fi
+local userdb="$1"
+
+echoAndLog "${FUNCNAME}(): checking if $userdb exists..."
+if [ "$(mysql --defaults-extra-file=$TMPMYCNF -Nse "SELECT user FROM mysql.user WHERE user='$userdb'")" == "$userdb" ]; then
+ echoAndLog "${FUNCNAME}(): user already exists"
+ return 0
+else
+ echoAndLog "${FUNCNAME}(): user doesn't exists"
+ return 1
+fi
+}
+
+# Crea un usuario administrativo para la base de datos
+function mysqlCreateAdminUserToDb()
+{
+ if [ $# -ne 3 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local database="$1"
+ local userdb="$2"
+ local passdb="$3"
+
+ echoAndLog "${FUNCNAME}(): creating admin user ${userdb} to database ${database}"
+
+ cat > $WORKDIR/create_${database}.sql <<EOF
+GRANT USAGE ON *.* TO '${userdb}'@'localhost' IDENTIFIED BY '${passdb}' ;
+GRANT ALL PRIVILEGES ON ${database}.* TO '${userdb}'@'localhost' WITH GRANT OPTION ;
+FLUSH PRIVILEGES ;
+EOF
+ mysql --defaults-extra-file=$TMPMYCNF < $WORKDIR/create_${database}.sql
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error while creating user in mysql"
+ rm -f $WORKDIR/create_${database}.sql
+ return 1
+ else
+ echoAndLog "${FUNCNAME}(): user created ok"
+ rm -f $WORKDIR/create_${database}.sql
+ return 0
+ fi
+}
+
+
+#####################################################################
+####### Funciones para la descarga de código
+#####################################################################
+
+# Obtiene el código fuente del proyecto desde el repositorio de GitHub.
+function downloadCode()
+{
+ if [ $# -ne 1 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local url="$1"
+
+ echoAndLog "${FUNCNAME}(): downloading code..."
+
+ curl "${url}" -o opengnsys.zip && unzip opengnsys.zip && mv "OpenGnsys-$BRANCH" opengnsys
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error getting OpenGnsys code from $url"
+ return 1
+ fi
+ rm -f opengnsys.zip
+ echoAndLog "${FUNCNAME}(): code was downloaded"
+ return 0
+}
+
+
+############################################################
+### Detectar red
+############################################################
+
+# Comprobar si existe conexión.
+function checkNetworkConnection()
+{
+echoAndLog "${FUNCNAME}(): Checking OpenGnsys server connectivity."
+OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"opengnsys.es"}
+curl --connect-timeout 10 -s $OPENGNSYS_SERVER -o /dev/null
+}
+
+# Convierte nº de bits (notación CIDR) en máscara de red (gracias a FriedZombie en openwrt.org).
+cidr2mask ()
+{
+ # Number of args to shift, 255..255, first non-255 byte, zeroes
+ set -- $[ 5 - ($1 / 8) ] 255 255 255 255 $[ (255 << (8 - ($1 % 8))) & 255 ] 0 0 0
+ [ $1 -gt 1 ] && shift $1 || shift
+ echo ${1-0}.${2-0}.${3-0}.${4-0}
+}
+
+# Obtener los parámetros de red de la interfaz por defecto.
+function getNetworkSettings()
+{
+ # Arrays globales definidas:
+ # - DEVICE: nombres de dispositivos de red activos.
+ # - SERVERIP: IPs locales del servidor.
+ # - NETIP: IPs de redes.
+ # - NETMASK: máscaras de red.
+ # - NETBROAD: IPs de difusión de redes.
+ # - ROUTERIP: IPs de routers.
+ # Otras variables globales:
+ # - DEFAULTDEV: dispositivo de red por defecto.
+ # - DNSIP: IP del servidor DNS principal.
+
+ local i=0
+ local dev=""
+
+ echoAndLog "${FUNCNAME}(): Detecting network parameters."
+ DEVICE=( $(ip -o link show up | awk '!/loopback/ {sub(/:.*/,"",$2); print $2}') )
+ if [ -z "$DEVICE" ]; then
+ errorAndLog "${FUNCNAME}(): Network devices not detected."
+ exit 1
+ fi
+ for dev in ${DEVICE[*]}; do
+ SERVERIP[i]=$(ip -o addr show dev "$dev" | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4)}')
+ if [ -n "${SERVERIP[i]}" ]; then
+ NETMASK[i]=$( cidr2mask $(ip -o addr show dev "$dev" | awk '$3~/inet$/ {sub (/.*\//, "", $4); print ($4)}') )
+ NETBROAD[i]=$(ip -o addr show dev "$dev" | awk '$3~/inet$/ {print ($6)}')
+ NETIP[i]=$(ip route list proto kernel | awk -v d="$dev" '$3==d && /src/ {sub (/\/.*/,""); print $1}')
+ ROUTERIP[i]=$(ip route list default | awk -v d="$dev" '$5==d {print $3}')
+ DEFAULTDEV=${DEFAULTDEV:-"$dev"}
+ fi
+ let i++
+ done
+ DNSIP=$(awk '/nameserver/ {print $2}' /etc/resolv.conf | head -n1)
+ if [ -z "${NETIP[*]}" -o -z "${NETMASK[*]}" ]; then
+ errorAndLog "${FUNCNAME}(): Network not detected."
+ exit 1
+ fi
+
+ # Variables de ejecución de Apache
+ # - APACHE_RUN_USER
+ # - APACHE_RUN_GROUP
+ if [ -f $APACHECFGDIR/envvars ]; then
+ source $APACHECFGDIR/envvars
+ fi
+ APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
+ APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
+
+ echoAndLog "${FUNCNAME}(): Default network device: $DEFAULTDEV."
+}
+
+
+############################################################
+### Esqueleto para el Servicio pxe y contenedor tftpboot ###
+############################################################
+
+function tftpConfigure()
+{
+ echoAndLog "${FUNCNAME}(): Configuring TFTP service."
+ # Habilitar TFTP y reiniciar Inetd.
+ if [ -n "$TFTPSERV" ]; then
+ if [ -f $INETDCFGDIR/$TFTPSERV ]; then
+ perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/$TFTPSERV
+ else
+ service=$TFTPSERV
+ $ENABLESERVICE; $STARTSERVICE
+ fi
+ fi
+ service=$INETDSERV
+ $ENABLESERVICE; $STARTSERVICE
+
+ # comprobamos el servicio tftp
+ sleep 1
+ testPxe
+}
+
+# Comprueba que haya conexión al servicio TFTP/PXE.
+function testPxe ()
+{
+ echoAndLog "${FUNCNAME}(): Checking TFTP service... please wait."
+ echo "test" >$TFTPCFGDIR/testpxe
+ tftp -v 127.0.0.1 -c get testpxe /tmp/testpxe && echoAndLog "TFTP service is OK." || errorAndLog "TFTP service is down."
+ rm -f $TFTPCFGDIR/testpxe /tmp/testpxe
+}
+
+
+########################################################################
+## Configuración servicio Samba
+########################################################################
+
+# Configurar servicios Samba.
+function smbConfigure()
+{
+ echoAndLog "${FUNCNAME}(): Configuring Samba service."
+
+ backupFile $SAMBACFGDIR/smb.conf
+
+ # Copiar plantailla de recursos para OpenGnsys
+ sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
+ $WORKDIR/opengnsys/server/etc/smb-og.conf.tmpl > $SAMBACFGDIR/smb-og.conf
+ # Configurar y recargar Samba"
+ perl -pi -e "s/WORKGROUP/OPENGNSYS/; s/server string \=.*/server string \= OpenGnsys Samba Server/" $SAMBACFGDIR/smb.conf
+ if ! grep -q "smb-og" $SAMBACFGDIR/smb.conf; then
+ echo "include = $SAMBACFGDIR/smb-og.conf" >> $SAMBACFGDIR/smb.conf
+ fi
+ service=$SAMBASERV
+ $ENABLESERVICE; $STARTSERVICE
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error while configure Samba"
+ return 1
+ fi
+ # Crear clave para usuario de acceso a los recursos.
+ echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | smbpasswd -a -s $OPENGNSYS_CLIENT_USER
+
+ echoAndLog "${FUNCNAME}(): Added Samba configuration."
+ return 0
+}
+
+
+########################################################################
+## Configuración servicio Rsync
+########################################################################
+
+# Configurar servicio Rsync.
+function rsyncConfigure()
+{
+ echoAndLog "${FUNCNAME}(): Configuring Rsync service."
+
+ backupFile $RSYNCCFGDIR/rsyncd.conf
+
+ # Configurar acceso a Rsync.
+ sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENT_USER/g" \
+ $WORKDIR/opengnsys/repoman/etc/rsyncd.conf.tmpl > $RSYNCCFGDIR/rsyncd.conf
+ sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENT_USER/g" \
+ -e "s/CLIENTPASSWORD/$OPENGNSYS_CLIENT_PASSWD/g" \
+ $WORKDIR/opengnsys/repoman/etc/rsyncd.secrets.tmpl > $RSYNCCFGDIR/rsyncd.secrets
+ chown root.root $RSYNCCFGDIR/rsyncd.secrets
+ chmod 600 $RSYNCCFGDIR/rsyncd.secrets
+
+ # Habilitar Rsync y reiniciar Inetd.
+ if [ -n "$RSYNCSERV" ]; then
+ if [ -f /etc/default/rsync ]; then
+ perl -pi -e 's/RSYNC_ENABLE=.*/RSYNC_ENABLE=inetd/' /etc/default/rsync
+ fi
+ if [ -f $INETDCFGDIR/rsync ]; then
+ perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/rsync
+ else
+ cat << EOT > $INETDCFGDIR/rsync
+service rsync
+{
+ disable = no
+ socket_type = stream
+ wait = no
+ user = root
+ server = $(which rsync)
+ server_args = --daemon
+ log_on_failure += USERID
+ flags = IPv6
+}
+EOT
+ fi
+ service=$RSYNCSERV $ENABLESERVICE
+ service=$INETDSERV $STARTSERVICE
+ fi
+
+ echoAndLog "${FUNCNAME}(): Added Rsync configuration."
+ return 0
+}
+
+
+########################################################################
+## Configuración servicio DHCP
+########################################################################
+
+# Configurar servicios DHCP.
+function dhcpConfigure()
+{
+ echoAndLog "${FUNCNAME}(): Sample DHCP configuration."
+
+ local errcode=0
+ local i=0
+ local dev=""
+
+ backupFile $DHCPCFGDIR/dhcpd.conf
+ for dev in ${DEVICE[*]}; do
+ if [ -n "${SERVERIP[i]}" ]; then
+ backupFile $DHCPCFGDIR/dhcpd-$dev.conf
+ sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
+ -e "s/NETIP/${NETIP[i]}/g" \
+ -e "s/NETMASK/${NETMASK[i]}/g" \
+ -e "s/NETBROAD/${NETBROAD[i]}/g" \
+ -e "s/ROUTERIP/${ROUTERIP[i]}/g" \
+ -e "s/DNSIP/$DNSIP/g" \
+ $WORKDIR/opengnsys/server/etc/dhcpd.conf.tmpl > $DHCPCFGDIR/dhcpd-$dev.conf || errcode=1
+ fi
+ let i++
+ done
+ if [ $errcode -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error while configuring DHCP server"
+ return 1
+ fi
+ ln -f $DHCPCFGDIR/dhcpd-$DEFAULTDEV.conf $DHCPCFGDIR/dhcpd.conf
+ service=$DHCPSERV
+ $ENABLESERVICE; $STARTSERVICE
+ echoAndLog "${FUNCNAME}(): Sample DHCP configured in \"$DHCPCFGDIR\"."
+ return 0
+}
+
+
+#####################################################################
+####### Funciones específicas de la instalación de Opengnsys
+#####################################################################
+
+# Instalar OpenGnsys Web Console.
+function installWebFiles()
+{
+local $tmpdir jsonfile=$INSTALL_TARGET/etc/opengnsys.json
+
+echoAndLog "${FUNCNAME}(): Copying backend files..."
+sed -e "s/ database_name:.*/ database_name: $OPENGNSYS_DATABASE/" \
+ -e "s/ database_user:.*/ database_user: $OPENGNSYS_DB_USER/" \
+ -e "s/ database_password:.*/ database_password: $OPENGNSYS_DB_PASSWD/" \
+ $WORKDIR/opengnsys/admin/WebConsole3/backend/app/config/parameters.yml.dist \
+ > $WORKDIR/opengnsys/admin/WebConsole3/backend/app/config/parameters.yml
+chown -R $OPENGNSYS_CLIENT_USER:$OPENGNSYS_CLIENT_USER $WORKDIR/opengnsys/admin/WebConsole3
+cp -a $WORKDIR/opengnsys/admin/WebConsole3/backend $INSTALL_TARGET/www3
+if [ $? != 0 ]; then
+ errorAndLog "${FUNCNAME}(): Error copying backend files."
+ exit 1
+fi
+
+echoAndLog "${FUNCNAME}(): Installing backend framework..."
+pushd $INSTALL_TARGET/www3/backend
+sudo -u $OPENGNSYS_CLIENT_USER composer.phar install
+chmod 777 -R var/cache var/logs
+sudo -u $OPENGNSYS_CLIENT_USER php app/console doctrine:database:create --if-not-exists
+sudo -u $OPENGNSYS_CLIENT_USER php app/console doctrine:schema:update --force
+echo yes | php app/console doctrine:fixtures:load
+php app/console fos:user:create "$OPENGNSYS_DB_USER" "${OPENGNSYS_DB_USER}@localhost.localdomain" "$OPENGNSYS_DB_USER"
+# Guardar tokens de seguridad.
+read -e APIID APISECRET <<< \
+ "$(php app/console doctrine:query:sql "SELECT random_id, secret FROM og_core__clients WHERE id=1;" | \
+ awk -F\" '$2~/^(random_id|secret)$/ {getline; printf("%s ", $2)}')"
+read -e CLIENTID CLIENTSECRET <<< \
+ "$(php app/console opengnsys:oauth-server:client:create --no-ansi \
+ --grant-type="password" --grant-type="refresh_token" \
+ --grant-type="token" \
+ --grant-type="http://opengnsys.es/grants/og_client" | \
+ awk 'BEGIN {RS=" "}
+ /^(id|secret)$/ {getline; gsub(/,/, ""); printf("%s ", $0)}')"
+[ -f $jsonfile ] || echo "{}" > $jsonfile
+jq '.client |= (. + {"id":"'"$CLIENTID"'", "secret":"'"$CLIENTSECRET"'"})' $jsonfile | sponge $jsonfile
+chown root $jsonfile
+chmod 600 $jsonfile
+popd
+
+echoAndLog "${FUNCNAME}(): Installing frontend framework..."
+pushd $WORKDIR/opengnsys/admin/WebConsole3/frontend
+tmpdir=$(sudo -u $OPENGNSYS_CLIENT_USER mktemp -d)
+echo "cache = $tmpdir" > .npmrc
+sudo -u $OPENGNSYS_CLIENT_USER npm install
+sed -i -e "s/SERVERIP/$SERVERIP/" \
+ -e "s/CLIENTID/1_$APIID/" \
+ -e "s/CLIENTSECRET/$APISECRET/" src/environments/environment.ts
+sed -i 's,base href=.*,base href="/opengnsys3/frontend/">,' src/index.html
+sudo -u $OPENGNSYS_CLIENT_USER ng build
+rm -fr $tmpdir
+
+echoAndLog "${FUNCNAME}(): Copying frontend files..."
+cp -a dist/opengnsysAngular6 $INSTALL_TARGET/www3/frontend
+if [ $? != 0 ]; then
+ errorAndLog "${FUNCNAME}(): Error copying frontend files."
+ exit 1
+fi
+popd
+
+echoAndLog "${FUNCNAME}(): Web files installed successfully."
+}
+
+# Copiar ficheros en la zona de descargas de OpenGnsys Web Console.
+function installDownloadableFiles()
+{
+ INSTVERSION=1.1.0 ### Temporal.
+ local FILENAME=ogagentpkgs-$INSTVERSION.tar.gz
+ local TARGETFILE=$WORKDIR/$FILENAME
+
+ # Descargar archivo comprimido, si es necesario.
+ if [ -s $PROGRAMDIR/$FILENAME ]; then
+ echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
+ mv $PROGRAMDIR/$FILENAME $TARGETFILE
+ else
+ echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
+ curl $DOWNLOADURL/$FILENAME -o $TARGETFILE
+ fi
+ if [ ! -s $TARGETFILE ]; then
+ errorAndLog "${FUNCNAME}(): Cannot download $FILENAME"
+ return 1
+ fi
+
+ # Descomprimir fichero en zona de descargas.
+ tar xvzf $TARGETFILE -C $INSTALL_TARGET/www/descargas
+ if [ $? != 0 ]; then
+ errorAndLog "${FUNCNAME}(): Error uncompressing archive."
+ exit 1
+ fi
+}
+
+# Configuración específica de Apache.
+function installWebConsoleApacheConf()
+{
+ if [ $# -ne 2 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local path_opengnsys_base="$1"
+ local path_apache2_confd="$2"
+ local CONSOLEDIR=${path_opengnsys_base}/www
+ local sockfile
+
+ if [ ! -d $path_apache2_confd ]; then
+ errorAndLog "${FUNCNAME}(): path to apache2 conf.d can not found, verify your server installation"
+ return 1
+ fi
+
+ mkdir -p $path_apache2_confd/{sites-available,sites-enabled}
+
+ echoAndLog "${FUNCNAME}(): creating apache2 config file.."
+
+ # Avtivar PHP-FPM.
+ echoAndLog "${FUNCNAME}(): configuring PHP-FPM"
+ service=$PHPFPMSERV
+ $ENABLESERVICE; $STARTSERVICE
+ sockfile=$(find /run/php -name "php*.sock" -type s -print 2>/dev/null | tail -1)
+
+ # Activar módulos de Apache.
+ $APACHEENABLEMODS
+ # Activar HTTPS.
+ $APACHEENABLESSL
+ $APACHEMAKECERT
+ # Genera configuración de consola web a partir del fichero plantilla.
+ if [ -n "$(apachectl -v | grep "2\.[0-2]")" ]; then
+ # Configuración para versiones anteriores de Apache.
+ sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
+ $WORKDIR/opengnsys/server/etc/apache-prev2.4.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}
+ else
+ # Configuración específica a partir de Apache 2.4
+ if [ -n "$sockfile" ]; then
+ sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
+ -e "s,proxy:fcgi:.*,proxy:unix:${sockfile%% *}|fcgi://localhost\",g" \
+ $WORKDIR/opengnsys/server/etc/apache.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf
+ else
+ sed -e "s,CONSOLEDIR,$CONSOLEDIR,g" \
+ $WORKDIR/opengnsys/server/etc/apache.conf.tmpl > $path_apache2_confd/$APACHESITESDIR/${APACHEOGSITE}.conf
+ fi
+ fi
+ $APACHEENABLEOG
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): config file can't be linked to apache conf, verify your server installation"
+ return 1
+ fi
+ echoAndLog "${FUNCNAME}(): config file created and linked, restarting apache daemon"
+ service=$APACHESERV
+ $ENABLESERVICE; $STARTSERVICE
+ return 0
+}
+
+
+# Crear documentación Doxygen para la consola web.
+function makeDoxygenFiles()
+{
+ echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
+ $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
+ $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
+ if [ ! -d "$INSTALL_TARGET/www/html" ]; then
+ errorAndLog "${FUNCNAME}(): unable to create Doxygen web files."
+ return 1
+ fi
+ mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
+ echoAndLog "${FUNCNAME}(): Doxygen web files created successfully."
+}
+
+
+# Crea la estructura base de la instalación de opengnsys
+function createDirs()
+{
+ if [ $# -ne 1 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local path_opengnsys_base="$1"
+
+ # Crear estructura de directorios.
+ echoAndLog "${FUNCNAME}(): creating directory paths in $path_opengnsys_base"
+ mkdir -p $path_opengnsys_base
+ mkdir -p $path_opengnsys_base/bin
+ mkdir -p $path_opengnsys_base/client/{cache,images,log}
+ mkdir -p $path_opengnsys_base/doc
+ mkdir -p $path_opengnsys_base/etc
+ mkdir -p $path_opengnsys_base/lib
+ mkdir -p $path_opengnsys_base/log/clients
+ ln -fs $path_opengnsys_base/log /var/log/opengnsys
+ mkdir -p $path_opengnsys_base/sbin
+ mkdir -p $path_opengnsys_base/www/descargas
+ mkdir -p $path_opengnsys_base/www3 ### TEMPORAL
+ mkdir -p $path_opengnsys_base/images/groups
+ mkdir -p $TFTPCFGDIR
+ ln -fs $TFTPCFGDIR $path_opengnsys_base/tftpboot
+ mkdir -p $path_opengnsys_base/tftpboot/{menu.lst,grub}
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
+ return 1
+ fi
+
+ # Crear usuario ficticio.
+ if id -u $OPENGNSYS_CLIENT_USER &>/dev/null; then
+ echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENT_USER\" is already created"
+ else
+ echoAndLog "${FUNCNAME}(): creating OpenGnsys user"
+ useradd $OPENGNSYS_CLIENT_USER 2>/dev/null
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error creating OpenGnsys user"
+ return 1
+ fi
+ fi
+
+ # Mover el fichero de registro de instalación al directorio de logs.
+ echoAndLog "${FUNCNAME}(): moving installation log file"
+ mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
+ chmod 600 $LOG_FILE
+
+ echoAndLog "${FUNCNAME}(): directory paths created"
+ return 0
+}
+
+# Copia ficheros de configuración y ejecutables genéricos del servidor.
+function copyServerFiles ()
+{
+ if [ $# -ne 1 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local path_opengnsys_base="$1"
+
+ # Lista de ficheros y directorios origen y de directorios destino.
+ local SOURCES=( server/tftpboot \
+ /usr/lib/shim/shimx64.efi.signed \
+ /usr/lib/grub/x86_64-efi-signed/grubnetx64.efi.signed \
+ server/bin \
+ repoman/bin \
+ server/lib \
+ admin/Sources/Services/ogAdmServerAux
+ admin/Sources/Services/ogAdmRepoAux
+ installer/opengnsys_uninstall.sh \
+ installer/opengnsys_update.sh \
+ installer/opengnsys_update3.sh \
+ installer/opengnsys_export.sh \
+ installer/opengnsys_import.sh \
+ doc )
+ local TARGETS=( tftpboot \
+ tftpboot \
+ tftpboot/grubx64.efi \
+ bin \
+ bin \
+ lib \
+ sbin \
+ sbin \
+ lib \
+ lib \
+ lib \
+ lib \
+ lib \
+ doc )
+
+ if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
+ errorAndLog "${FUNCNAME}(): inconsistent number of array items"
+ exit 1
+ fi
+
+ # Copiar ficheros.
+ echoAndLog "${FUNCNAME}(): copying files to server directories"
+
+ pushd $WORKDIR/opengnsys
+ local i
+ for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
+ if [ -f "${SOURCES[$i]}" ]; then
+ echoAndLog "Copying ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
+ cp -a "${SOURCES[$i]}" "${path_opengnsys_base}/${TARGETS[$i]}"
+ elif [ -d "${SOURCES[$i]}" ]; then
+ echoAndLog "Copying content of ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
+ cp -a "${SOURCES[$i]}"/* "${path_opengnsys_base}/${TARGETS[$i]}"
+ else
+ warningAndLog "Unable to copy ${SOURCES[$i]} to $path_opengnsys_base/${TARGETS[$i]}"
+ fi
+ done
+
+ popd
+}
+
+
+####################################################################
+### Funciones de copia de la Interface de administración
+####################################################################
+
+# Copiar carpeta de Interface
+function copyInterfaceAdm ()
+{
+ local hayErrores=0
+
+ # Crear carpeta y copiar Interface
+ echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
+ cp -ar $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client/interfaceAdm
+ if [ $? -ne 0 ]; then
+ echoAndLog "${FUNCNAME}(): error while copying Administration Interface Folder"
+ hayErrores=1
+ fi
+ chown $OPENGNSYS_CLIENT_USER:$OPENGNSYS_CLIENT_USER $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
+ chmod 700 $INSTALL_TARGET/client/interfaceAdm/CambiarAcceso
+
+ return $hayErrores
+}
+
+####################################################################
+### Funciones instalacion cliente opengnsys
+####################################################################
+
+function copyClientFiles()
+{
+ local errstatus=0
+
+ echoAndLog "${FUNCNAME}(): Copying OpenGnsys Client files."
+ cp -a $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error while copying client estructure"
+ errstatus=1
+ fi
+
+ echoAndLog "${FUNCNAME}(): Copying OpenGnsys Cloning Engine files."
+ mkdir -p $INSTALL_TARGET/client/lib/engine/bin
+ cp -a $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error while copying engine files"
+ errstatus=1
+ fi
+
+ if [ $errstatus -eq 0 ]; then
+ echoAndLog "${FUNCNAME}(): client copy files success."
+ else
+ errorAndLog "${FUNCNAME}(): client copy files with errors"
+ fi
+
+ return $errstatus
+}
+
+
+# Crear cliente OpenGnsys.
+function clientCreate()
+{
+ if [ $# -ne 1 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local FILENAME="$1"
+ local TARGETFILE=$INSTALL_TARGET/lib/$FILENAME
+
+ # Descargar cliente, si es necesario.
+ if [ -s $PROGRAMDIR/$FILENAME ]; then
+ echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
+ mv $PROGRAMDIR/$FILENAME $TARGETFILE
+ else
+ echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
+ oglivecli download $FILENAME
+ fi
+ if [ ! -s $TARGETFILE ]; then
+ errorAndLog "${FUNCNAME}(): Error loading $FILENAME"
+ return 1
+ fi
+
+ # Montar imagen, copiar cliente ogclient y desmontar.
+ echoAndLog "${FUNCNAME}(): Installing ogLive Client"
+ echo -ne "$OPENGNSYS_CLIENT_PASSWD\n$OPENGNSYS_CLIENT_PASSWD\n" | \
+ oglivecli install $FILENAME
+ # Adaptar permisos.
+ chown -R $APACHE_RUN_USER:$APACHE_RUN_GROUP $INSTALL_TARGET/tftpboot/menu.lst
+
+ echoAndLog "${FUNCNAME}(): Client generation success"
+}
+
+
+# Función temporal para generar y copiar el agente OGAgent para ogLive
+function createOgagentPackage ()
+{
+local ogagentdir=$WORKDIR/opengnsys/admin/Sources/Clients/ogagent/oglive
+
+echoAndLog "${FUNCNAME}(): Creating OGAgent for ogLive package..."
+OGAGENTFILE=$($ogagentdir/build-package.sh | awk -F\' '/building package/ {print $(NF-1)}')
+if [ -z "$OGAGENTFILE" ]; then
+ errorAndLog "${FUNCNAME}(): Error generating OGAgent pacakage."
+ return 1
+fi
+OGAGENTFILE=$(realpath $ogagentdir/$OGAGENTFILE)
+cp -va $OGAGENTFILE $INSTALL_TARGET/images
+echoAndLog "${FUNCNAME}(): OGAgent for ogLive package has been copied to the repository"
+}
+
+
+# Configuración básica de servicios de OpenGnsys
+function openGnsysConfigure()
+{
+ local i=0
+ local dev=""
+ local CONSOLEURL
+
+ echoAndLog "${FUNCNAME}(): Copying init files."
+ cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
+ cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default /etc/default/opengnsys
+ # Deshabilitar servicios de BitTorrent si no están instalados.
+ if [ ! -e /usr/bin/bttrack ]; then
+ sed -i 's/RUN_BTTRACKER="yes"/RUN_BTTRACKER="no"/; s/RUN_BTSEEDER="yes"/RUN_BTSEEDER="no"/' \
+ /etc/default/opengnsys
+ fi
+ echoAndLog "${FUNCNAME}(): Creating cron files."
+ echo "* * * * * root [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
+ echo "* * * * * root [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
+ echo "5 * * * * root [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
+ echo "* * * * * root [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
+ echo "* * * * * root [ -x $INSTALL_TARGET/bin/ogagentqueue.cron ] && $INSTALL_TARGET/bin/ogagentqueue.cron" > /etc/cron.d/ogagentqueue
+
+ echoAndLog "${FUNCNAME}(): Creating logrotate configuration files."
+ sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
+ $WORKDIR/opengnsys/server/etc/logrotate.tmpl > /etc/logrotate.d/opengnsysServer
+
+ sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
+ $WORKDIR/opengnsys/repoman/etc/logrotate.tmpl > /etc/logrotate.d/opengnsysRepo
+
+ echoAndLog "${FUNCNAME}(): Creating OpenGnsys config files."
+ for dev in ${DEVICE[*]}; do
+ if [ -n "${SERVERIP[i]}" ]; then
+ sed -e "s/SERVERIP/${SERVERIP[i]}/g" \
+ -e "s/REPOKEY/$OPENGNSYS_REPOKEY/g" \
+ $WORKDIR/opengnsys/repoman/etc/ogAdmRepo.cfg.tmpl > $INSTALL_TARGET/etc/ogAdmRepo-$dev.cfg
+ if [ "$dev" == "$DEFAULTDEV" ]; then
+ OPENGNSYS_CONSOLEURL="$CONSOLEURL"
+ fi
+ fi
+ let i++
+ done
+ ln -f $INSTALL_TARGET/etc/ogAdmRepo-$DEFAULTDEV.cfg $INSTALL_TARGET/etc/ogAdmRepo.cfg
+
+ # Configuración del motor de clonación.
+ # - Zona horaria del servidor.
+ TZ=$(timedatectl status|awk -F"[:()]" '/Time.*zone/ {print $2}')
+ cat << EOT >> $INSTALL_TARGET/client/etc/engine.cfg
+# OpenGnsys Server timezone.
+TZ="${TZ// /}"
+EOT
+
+ # Revisar permisos generales.
+ if [ -x $INSTALL_TARGET/bin/checkperms ]; then
+ echoAndLog "${FUNCNAME}(): Checking permissions."
+ OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENT_USER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" checkperms
+ fi
+
+ # Evitar inicio de duplicado en Ubuntu 14.04 (Upstart y SysV Init).
+ if [ -f /etc/init/${MYSQLSERV}.conf -a -n "$(which initctl 2>/dev/null)" ]; then
+ service=$MYSQLSERV
+ $DISABLESERVICE
+ fi
+}
+
+
+#####################################################################
+####### Función de resumen informativo de la instalación
+#####################################################################
+
+function installationSummary()
+{
+ local VERSIONFILE REVISION
+
+ # Crear fichero de versión y revisión, si no existe.
+ VERSIONFILE="$INSTALL_TARGET/doc/VERSION.json"
+ [ -f $VERSIONFILE ] || echo '{ "project": "OpenGnsys" }' >$VERSIONFILE
+ # Incluir datos de revisión, si se está instalando desde el repositorio
+ # de código o si no está incluida en el fichero de versión.
+ if [ $REMOTE -eq 1 ] || [ -z "$(jq -r '.release' $VERSIONFILE)" ]; then
+ # Revisión: rAñoMesDía.Gitcommit (8 caracteres de fecha y 7 primeros de commit).
+ REVISION=$(curl -s "$API_URL" | jq '"r" + (.commit.commit.committer.date | split("-") | join("")[:8]) + "." + (.commit.sha[:7])')
+ jq ".release=$REVISION" $VERSIONFILE | sponge $VERSIONFILE
+ fi
+ VERSION="$(jq -r '[.project, .version, .codename, .release] | join(" ")' $VERSIONFILE 2>/dev/null)"
+
+ # Mostrar información.
+ echo
+ echoAndLog "OpenGnsys Installation Summary"
+ echo "=============================="
+ echoAndLog "Project version: $VERSION"
+ echoAndLog "Installation directory: $INSTALL_TARGET"
+ echoAndLog "Installation log file: $LOG_FILE"
+ echoAndLog "Repository directory: $INSTALL_TARGET/images"
+ echoAndLog "DHCP configuration directory: $DHCPCFGDIR"
+ echoAndLog "TFTP configuration directory: $TFTPCFGDIR"
+ echoAndLog "Installed ogLive client(s): $(oglivecli list | awk '{print $2}')"
+ echoAndLog "Samba configuration directory: $SAMBACFGDIR"
+ echoAndLog "Web Console URL: $OPENGNSYS_CONSOLEURL"
+ echoAndLog "Web Console access data: entered by the user"
+ if grep -q "^RUN_BTTRACK.*no" /etc/default/opengnsys; then
+ echoAndLog "BitTorrent service is disabled."
+ fi
+ echo
+ echoAndLog "Post-Installation Instructions:"
+ echo "==============================="
+ echoAndLog "You can improve server security by configuring firewall and SELinux,"
+ echoAndLog " running \"$INSTALL_TARGET/lib/security-config\" script as root."
+ echoAndLog "It's strongly recommended to synchronize this server with an NTP server."
+ echoAndLog "Review or edit all configuration files."
+ echoAndLog "Insert DHCP configuration data and restart service."
+ echoAndLog "Optional: Log-in as Web Console admin user."
+ echoAndLog " - Review default Organization data and assign access to users."
+ echoAndLog "Log-in as Web Console organization user."
+ echoAndLog " - Insert OpenGnsys data (labs, computers, menus, etc)."
+echo
+}
+
+
+
+#####################################################################
+####### Proceso de instalación de OpenGnsys
+#####################################################################
+
+echoAndLog "OpenGnsys installation begins at $(date)"
+pushd $WORKDIR
+
+# Detectar datos iniciales de auto-configuración del instalador.
+autoConfigure
+
+# Detectar parámetros de red y comprobar si hay conexión.
+getNetworkSettings
+if [ $? -ne 0 ]; then
+ errorAndLog "Error reading default network settings."
+ exit 1
+fi
+checkNetworkConnection
+if [ $? -ne 0 ]; then
+ errorAndLog "Error connecting to server. Causes:"
+ errorAndLog " - Network is unreachable, review devices parameters."
+ errorAndLog " - You are inside a private network, configure the proxy service."
+ errorAndLog " - Server is temporally down, try agian later."
+ exit 1
+fi
+
+# Detener servicios de OpenGnsys, si están activos previamente.
+[ -f /etc/init.d/opengnsys ] && /etc/init.d/opengnsys stop
+
+# Actualizar repositorios
+updatePackageList
+
+# Instalación de dependencias (paquetes de sistema operativo).
+declare -a notinstalled
+checkDependencies DEPENDENCIES notinstalled
+if [ $? -ne 0 ]; then
+ installDependencies notinstalled
+ if [ $? -ne 0 ]; then
+ echoAndLog "Error while installing some dependeces, please verify your server installation before continue"
+ exit 1
+ fi
+fi
+if [ -n "$INSTALLEXTRADEPS" ]; then
+ echoAndLog "Installing extra dependencies"
+ for (( i=0; i<${#INSTALLEXTRADEPS[*]}; i++ )); do
+ eval ${INSTALLEXTRADEPS[i]}
+ done
+fi
+
+# Detectar datos de auto-configuración después de instalar paquetes.
+autoConfigurePost
+
+# Arbol de directorios de OpenGnsys.
+createDirs ${INSTALL_TARGET}
+if [ $? -ne 0 ]; then
+ errorAndLog "Error while creating directory paths!"
+ exit 1
+fi
+
+# Si es necesario, descarga el repositorio de código en directorio temporal
+if [ $REMOTE -eq 1 ]; then
+ downloadCode $CODE_URL
+ if [ $? -ne 0 ]; then
+ errorAndLog "Error while getting code from the repository"
+ exit 1
+ fi
+else
+ ln -fs "$(dirname $PROGRAMDIR)" opengnsys
+fi
+
+# Copiar carpeta Interface entre administración y motor de clonación.
+copyInterfaceAdm
+if [ $? -ne 0 ]; then
+ errorAndLog "Error while copying Administration Interface"
+ exit 1
+fi
+
+# Configuración de TFTP.
+tftpConfigure
+
+# Configuración de Samba.
+smbConfigure
+if [ $? -ne 0 ]; then
+ errorAndLog "Error while configuring Samba server!"
+ exit 1
+fi
+
+# Configuración de Rsync.
+rsyncConfigure
+
+# Configuración ejemplo DHCP.
+dhcpConfigure
+if [ $? -ne 0 ]; then
+ errorAndLog "Error while copying your dhcp server files!"
+ exit 1
+fi
+
+# Copiar ficheros de servicios OpenGnsys Server.
+copyServerFiles ${INSTALL_TARGET}
+if [ $? -ne 0 ]; then
+ errorAndLog "Error while copying the server files!"
+ exit 1
+fi
+INSTVERSION=$(jq -r '.version' $INSTALL_TARGET/doc/VERSION.json)
+
+# Instalar base de datos de OpenGnsys Admin.
+isInArray notinstalled "mysql-server" || isInArray notinstalled "mariadb-server"
+if [ $? -eq 0 ]; then
+ # Habilitar gestor de base de datos (MySQL, si falla, MariaDB).
+ service=$MYSQLSERV
+ $ENABLESERVICE
+ if [ $? != 0 ]; then
+ service=$MARIADBSERV
+ $ENABLESERVICE
+ fi
+ # Activar gestor de base de datos.
+ $STARTSERVICE
+ # Asignar clave del usuario "root".
+ mysqlSetRootPassword "${MYSQL_ROOT_PASSWORD}"
+else
+ # Si ya está instalado el gestor de bases de datos, obtener clave de "root",
+ mysqlGetRootPassword
+fi
+
+mysqlTestConnection "${MYSQL_ROOT_PASSWORD}"
+if [ $? -ne 0 ]; then
+ errorAndLog "Error while connection to mysql"
+ exit 1
+fi
+mysqlDbExists ${OPENGNSYS_DATABASE}
+if [ $? -ne 0 ]; then
+ echoAndLog "Creating Web Console database"
+ mysqlCreateDb ${OPENGNSYS_DATABASE}
+ if [ $? -ne 0 ]; then
+ errorAndLog "Error while creating Web Console database"
+ exit 1
+ fi
+else
+ echoAndLog "Web Console database exists, ommiting creation"
+fi
+
+mysqlCheckUserExists ${OPENGNSYS_DB_USER}
+if [ $? -ne 0 ]; then
+ echoAndLog "Creating user in database"
+ mysqlCreateAdminUserToDb ${OPENGNSYS_DATABASE} ${OPENGNSYS_DB_USER} "${OPENGNSYS_DB_PASSWD}"
+ if [ $? -ne 0 ]; then
+ errorAndLog "Error while creating database user"
+ exit 1
+ fi
+
+fi
+rm -f $TMPMYCNF
+
+# Copiando páqinas web.
+installWebFiles
+# Descargar/descomprimir archivos descargables.
+installDownloadableFiles
+# Generar páqinas web de documentación de la API
+makeDoxygenFiles
+
+# Creando configuración de Apache.
+installWebConsoleApacheConf $INSTALL_TARGET $APACHECFGDIR
+if [ $? -ne 0 ]; then
+ errorAndLog "Error configuring Apache for OpenGnsys Admin"
+ exit 1
+fi
+
+popd
+
+# Crear la estructura de los accesos al servidor desde el cliente (shared)
+copyClientFiles
+if [ $? -ne 0 ]; then
+ errorAndLog "Error creating client structure"
+fi
+
+# Crear la estructura del cliente de OpenGnsys.
+for i in $OGLIVE; do
+ if ! clientCreate "$i"; then
+ errorAndLog "Error creating client $i"
+ exit 1
+ fi
+done
+
+# Copiar paquete ogagent-oglive en el repositorio.
+createOgagentPackage
+
+# Configuración de servicios de OpenGnsys
+openGnsysConfigure
+
+# Mostrar sumario de la instalación e instrucciones de post-instalación.
+installationSummary
+
+#rm -rf $WORKDIR
+echoAndLog "OpenGnsys installation finished at $(date)"
+exit 0
+
diff --git a/installer/opengnsys_update.sh b/installer/opengnsys_update.sh
index 265853ae..826e9b89 100755
--- a/installer/opengnsys_update.sh
+++ b/installer/opengnsys_update.sh
@@ -118,7 +118,7 @@ function autoConfigure()
# Configuración según la distribución de Linux.
if [ -f /etc/debian_version ]; then
# Distribución basada en paquetes Deb.
- DEPENDENCIES=( curl rsync btrfs-tools procps arp-scan realpath php-curl gettext moreutils jq udpcast libev-dev shim-signed grub-efi-amd64-signed php-fpm git libcurl3 nodejs npm php-mbstring php-xml )
+ DEPENDENCIES=( curl rsync btrfs-tools procps arp-scan realpath php-curl gettext moreutils jq udpcast libev-dev shim-signed grub-efi-amd64-signed php-fpm )
# Paquete correcto para realpath.
[ -z "$(apt-cache pkgnames realpath)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//realpath/coreutils} )
UPDATEPKGLIST="add-apt-repository -y ppa:ondrej/php; apt-get update"
@@ -143,7 +143,7 @@ function autoConfigure()
INETDCFGDIR=/etc/xinetd.d
elif [ -f /etc/redhat-release ]; then
# Distribución basada en paquetes rpm.
- DEPENDENCIES=( curl rsync btrfs-progs procps-ng arp-scan gettext moreutils jq net-tools udpcast libev-devel shim-x64 grub2-efi-x64 grub2-efi-x64-modules git libcurl3 nodejs npm php-mbstring php-xml )
+ DEPENDENCIES=( curl rsync btrfs-progs procps-ng arp-scan gettext moreutils jq net-tools udpcast libev-devel shim-x64 grub2-efi-x64 grub2-efi-x64-modules )
# Repositorios para PHP 7 en CentOS.
[ "$OSDISTRIB" == "centos" ] && UPDATEPKGLIST="yum update -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-$OSVERSION.noarch.rpm http://rpms.remirepo.net/enterprise/remi-release-$OSVERSION.rpm"
INSTALLPKGS="yum install -y"
@@ -302,7 +302,6 @@ function importSqlFile()
local mycnf=/tmp/.my.cnf.$$
local status
local APIKEY=$(php -r 'echo md5(uniqid(rand(), true));')
- REPOKEY=$(php -r 'echo md5(uniqid(rand(), true));')
if [ ! -r $sqlfile ]; then
errorAndLog "${FUNCNAME}(): Unable to read $sqlfile!!"
@@ -376,7 +375,7 @@ function installDependencies()
eval $UPDATEPKGLIST
if [ -f /etc/debian_version ]; then
# Basado en paquetes Deb.
- PHP7VERSION=$(apt-cache pkgnames php7 2>/dev/null | grep -v -- - | sort | tail -1)
+ PHP7VERSION=$(apt-cache pkgnames php7 2>/dev/null | sort | head -1)
PHPFPMSERV="${PHP7VERSION}-fpm"
PHP5PKGS=( $(dpkg -l | awk '$2~/^php5/ {print $2}') )
if [ -n "$PHP5PKGS" ]; then
@@ -430,7 +429,10 @@ function downloadCode()
echoAndLog "${FUNCNAME}(): downloading code..."
- curl "${url}" -o opengnsys.zip && unzip opengnsys.zip && mv "OpenGnsys-$BRANCH" opengnsys
+ curl "$url" -o opengnsys.zip && \
+ unzip -qo opengnsys.zip && \
+ rm -fr opengnsys && \
+ mv "OpenGnsys-$BRANCH" opengnsys
if [ $? -ne 0 ]; then
errorAndLog "${FUNCNAME}(): error getting code from ${url}, verify your user and password"
return 1
@@ -565,13 +567,6 @@ function apacheConfiguration ()
echoAndLog "${FUNCNAME}(): Configuring Apache modules"
sed -i '/rewrite/s/^#//' $APACHECFGDIR/*.conf
fi
- # Habilitar nueva web.
- if [ ! -e $APACHECFGDIR/sites-available/opengnsys3.conf ]; then
- sed -e "s,CONSOLEDIR3,$INSTALL_TARGET/www3,g" \
- $WORKDIR/opengnsys/server/etc/apache-console3.conf.tmpl > $APACHECFGDIR/sites-available/opengnsys3.conf
- a2dissite opengnsys
- a2ensite opengnsys3
- fi
# Elegir plantilla según versión de Apache.
if [ -n "$(apachectl -v | grep "2\.[0-2]")" ]; then
template=$WORKDIR/opengnsys/server/etc/apache-prev2.4.conf.tmpl > $config
@@ -685,57 +680,6 @@ function updateWebFiles()
echoAndLog "${FUNCNAME}(): Web files successfully updated"
}
-# Instalar dependencias y copiar ficheros de la nueva web de OpenGnsys 3.
-function updateWeb3()
-{
- echoAndLog "${FUNCNAME}(): Installing OpenGnsys 3 Web Console..."
- # Copiar ficheros.
- mkdir -p $INSTALL_TARGET/www3
- cp -a $WORKDIR/opengnsys/admin/WebConsole3/backend $INSTALL_TARGET/www3
-
- # Instalar Composer.
- if [ ! -f /usr/local/bin/composer.phar ]; then
- php -r "copy('https://getcomposer.org/installer', '/tmp/composer-setup.php');"
- php /tmp/composer-setup.php --install-dir=/usr/local/bin
- rm -f /tmp/composer-setup.php
- fi
- # Instalar dependencias y migrar la BD para el backend.
- pushd $INSTALL_TARGET/www3/backend
- composer.phar update
- chmod 777 -R var/cache var/logs
- echo "Enter MySQL root password: "
- mysql -u root -p <<< "
- CREATE DATABASE IF NOT EXISTS ${OPENGNSYS_DATABASE}3;
- GRANT ALL PRIVILEGES ON ${OPENGNSYS_DATABASE}3.* TO $OPENGNSYS_DBUSER IDENTIFIED BY '$OPENGNSYS_DBPASSWORD';
-"
- # Crear la base de datos
- php app/console doctrine:database:create --if-not-exists
- # Actualizar el esquema de la base de datos
- php app/console doctrine:schema:update --force
- php app/console doctrine:fixtures:load
- # Crear el usuario con permisos de Administrador
- php app/console fos:user:create admin admin@localhost.localdomain admin
- # Crear el cliente Auth2 para obtener us client_id y secret
- php app/console opengnsys:oauth-server:client:create --grant-type="password" --grant-type="refresh_token" --grant-type="token" --grant-type="http://opengnsys.es/grants/og_client"
- # Realizar la migración de la versión anterior de opengnsys 1.1
- php app/console opengnsys:migration:execute
- popd
-
- # Instalar NodeJs y NG.
- curl -sL https://deb.nodesource.com/setup_10.x | bash -
- apt install nodejs
- [ -L /usr/bin/node ] || ln -s /usr/bin/nodejs /usr/bin/node
- npm install -g @angular/cli@6.2.3
- # Instalar el frontend.
- pushd $WORKDIR/opengnsys/admin/WebConsole3/frontend
- npm install
- sed -i "s/SERVERIP/$SERVERIP/" src/environments/environment.ts
- sed -i 's,base href=.*,base href="/opengnsys3/frontend/">,' src/index.html
- ng build
- rsync -irplt dist/opengnsysAngular6/* $INSTALL_TARGET/www3/frontend
- popd
-}
-
# Copiar ficheros en la zona de descargas de OpenGnsys Web Console.
function updateDownloadableFiles()
{
@@ -883,6 +827,7 @@ function updateDatabase()
fi
popd >/dev/null
+ REPOKEY=$(php -r 'echo md5(uniqid(rand(), true));')
if [ -n "$FILES" ]; then
for file in $FILES; do
importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $DBDIR/$file
@@ -1270,16 +1215,13 @@ rsyncConfigure
updateClientFiles
updateInterfaceAdm
-# Actualizar antigua páqina web
+# Actualizar páqinas web
apacheConfiguration
updateWebFiles
if [ $? -ne 0 ]; then
errorAndLog "Error updating OpenGnsys Web Admin files"
exit 1
fi
-# Actualizar nueva página web
-updateWeb3
-
# Actaulizar ficheros descargables.
updateDownloadableFiles
# Generar páginas Doxygen para instalar en el web
diff --git a/installer/opengnsys_update3.sh b/installer/opengnsys_update3.sh
new file mode 100755
index 00000000..265853ae
--- /dev/null
+++ b/installer/opengnsys_update3.sh
@@ -0,0 +1,1308 @@
+#!/bin/bash
+#/**
+#@file opengnsys_update.sh
+#@brief Script actualización de OpenGnsys
+#@version 0.9 - basado en opengnsys_installer.sh
+#@author Ramón Gómez - ETSII Univ. Sevilla
+#@date 2010/01/27
+#@version 1.0 - adaptación a OpenGnSys 1.0
+#@author Ramón Gómez - ETSII Univ. Sevilla
+#@date 2011/03/02
+#@version 1.0.1 - control de auto actualización del script
+#@author Ramón Gómez - ETSII Univ. Sevilla
+#@date 2011/05/17
+#@version 1.0.2a - obtiene valor de dirección IP por defecto
+#@author Ramón Gómez - ETSII Univ. Sevilla
+#@date 2012/01/18
+#@version 1.0.3 - Compatibilidad con Debian y auto configuración de acceso a BD.
+#@author Ramón Gómez - ETSII Univ. Sevilla
+#@date 2012/03/12
+#@version 1.0.4 - Detector de distribución y compatibilidad con CentOS.
+#@author Ramón Gómez - ETSII Univ. Sevilla
+#@date 2012/05/04
+#@version 1.0.5 - Actualizar BD en la misma versión, compatibilidad con Fedora (systemd) y configuración de Rsync.
+#@author Ramón Gómez - ETSII Univ. Sevilla
+#@date 2014/04/03
+#@version 1.0.6 - Redefinir URLs de ficheros de configuración usando HTTPS.
+#@author Ramón Gómez - ETSII Univ. Sevilla
+#@date 2015/03/12
+#@version 1.1.0 - Instalación de API REST y configuración de zona horaria.
+#@author Ramón Gómez - ETSII Univ. Sevilla
+#@date 2015/11/09
+#*/
+
+
+#### AVISO: NO EDITAR variables de configuración.
+#### WARNING: DO NOT EDIT configuration variables.
+INSTALL_TARGET=/opt/opengnsys # Directorio de instalación
+PATH=$PATH:$INSTALL_TARGET/bin
+OPENGNSYS_CLIENTUSER="opengnsys" # Usuario Samba
+
+
+# Sólo ejecutable por usuario root
+if [ "$(whoami)" != 'root' ]; then
+ echo "ERROR: this program must run under root privileges!!"
+ exit 1
+fi
+# Error si OpenGnsys no está instalado (no existe el directorio del proyecto)
+if [ ! -d $INSTALL_TARGET ]; then
+ echo "ERROR: OpenGnsys is not installed, cannot update!!"
+ exit 1
+fi
+# Cargar configuración de acceso a la base de datos.
+if [ -r $INSTALL_TARGET/etc/ogAdmServer.cfg ]; then
+ source $INSTALL_TARGET/etc/ogAdmServer.cfg
+elif [ -r $INSTALL_TARGET/etc/ogAdmAgent.cfg ]; then
+ source $INSTALL_TARGET/etc/ogAdmAgent.cfg
+fi
+OPENGNSYS_DATABASE=${OPENGNSYS_DATABASE:-"$CATALOG"} # Base de datos
+OPENGNSYS_DBUSER=${OPENGNSYS_DBUSER:-"$USUARIO"} # Usuario de acceso
+OPENGNSYS_DBPASSWORD=${OPENGNSYS_DBPASSWORD:-"$PASSWORD"} # Clave del usuario
+if [ -z "$OPENGNSYS_DATABASE" -o -z "$OPENGNSYS_DBUSER" -o -z "$OPENGNSYS_DBPASSWORD" ]; then
+ echo "ERROR: set OPENGNSYS_DATABASE, OPENGNSYS_DBUSER and OPENGNSYS_DBPASSWORD"
+ echo " variables, and run this script again."
+ exit 1
+fi
+
+# Comprobar si se ha descargado el paquete comprimido (REMOTE=0) o sólo el instalador (REMOTE=1).
+PROGRAMDIR=$(readlink -e $(dirname "$0"))
+PROGRAMNAME=$(basename "$0")
+OPENGNSYS_SERVER="opengnsys.es"
+if [ -d "$PROGRAMDIR/../installer" ]; then
+ REMOTE=0
+else
+ REMOTE=1
+fi
+BRANCH="devel"
+CODE_URL="https://codeload.github.com/opengnsys/OpenGnsys/zip/$BRANCH"
+API_URL="https://api.github.com/repos/opengnsys/OpenGnsys/branches/$BRANCH"
+RAW_URL="https://raw.githubusercontent.com/opengnsys/OpenGnsys/$BRANCH"
+
+WORKDIR=/tmp/opengnsys_update
+mkdir -p $WORKDIR
+
+# Registro de incidencias.
+OGLOGFILE=$INSTALL_TARGET/log/${PROGRAMNAME%.sh}.log
+LOG_FILE=/tmp/$(basename $OGLOGFILE)
+
+
+
+#####################################################################
+####### Algunas funciones útiles de propósito general:
+#####################################################################
+
+# Generar variables de configuración del actualizador
+# Variables globales:
+# - OSDISTRIB - distribución Linux
+# - DEPENDENCIES - array de dependencias que deben estar instaladas
+# - UPDATEPKGLIST, INSTALLPKGS, CHECKPKG - comandos para gestión de paquetes
+# - APACHECFGDIR, APACHESERV, PHPFPMSERV, DHCPSERV, INETDCFGDIR - configuración y servicios
+
+function autoConfigure()
+{
+ local service
+
+ # Detectar sistema operativo del servidor (compatible con fichero os-release y con LSB).
+ if [ -f /etc/os-release ]; then
+ source /etc/os-release
+ OSDISTRIB="$ID"
+ OSVERSION="$VERSION_ID"
+ else
+ OSDISTRIB=$(lsb_release -is 2>/dev/null)
+ OSVERSION=$(lsb_release -rs 2>/dev/null)
+ fi
+ # Convertir distribución a minúsculas y obtener solo el 1er número de versión.
+ OSDISTRIB="${OSDISTRIB,,}"
+ OSVERSION="${OSVERSION%%.*}"
+
+ # Configuración según la distribución de Linux.
+ if [ -f /etc/debian_version ]; then
+ # Distribución basada en paquetes Deb.
+ DEPENDENCIES=( curl rsync btrfs-tools procps arp-scan realpath php-curl gettext moreutils jq udpcast libev-dev shim-signed grub-efi-amd64-signed php-fpm git libcurl3 nodejs npm php-mbstring php-xml )
+ # Paquete correcto para realpath.
+ [ -z "$(apt-cache pkgnames realpath)" ] && DEPENDENCIES=( ${DEPENDENCIES[@]//realpath/coreutils} )
+ UPDATEPKGLIST="add-apt-repository -y ppa:ondrej/php; apt-get update"
+ INSTALLPKGS="apt-get -y install"
+ DELETEPKGS="apt-get -y purge"
+ CHECKPKG="dpkg -s \$package 2>/dev/null | grep -q \"Status: install ok\""
+ if which service &>/dev/null; then
+ STARTSERVICE="eval service \$service restart"
+ STOPSERVICE="eval service \$service stop"
+ SERVICESTATUS="eval service \$service status"
+ else
+ STARTSERVICE="eval /etc/init.d/\$service restart"
+ STOPSERVICE="eval /etc/init.d/\$service stop"
+ SERVICESTATUS="eval /etc/init.d/\$service status"
+ fi
+ ENABLESERVICE="eval update-rc.d \$service defaults"
+ APACHEENABLEMODS="ssl rewrite proxy_fcgi fastcgi actions alias"
+ APACHEDISABLEMODS="php"
+ APACHEUSER="www-data"
+ APACHEGROUP="www-data"
+ PHPFPMSERV="php-fpm"
+ INETDCFGDIR=/etc/xinetd.d
+ elif [ -f /etc/redhat-release ]; then
+ # Distribución basada en paquetes rpm.
+ DEPENDENCIES=( curl rsync btrfs-progs procps-ng arp-scan gettext moreutils jq net-tools udpcast libev-devel shim-x64 grub2-efi-x64 grub2-efi-x64-modules git libcurl3 nodejs npm php-mbstring php-xml )
+ # Repositorios para PHP 7 en CentOS.
+ [ "$OSDISTRIB" == "centos" ] && UPDATEPKGLIST="yum update -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-$OSVERSION.noarch.rpm http://rpms.remirepo.net/enterprise/remi-release-$OSVERSION.rpm"
+ INSTALLPKGS="yum install -y"
+ DELETEPKGS="yum remove -y"
+ CHECKPKG="rpm -q --quiet \$package"
+ if which systemctl &>/dev/null; then
+ STARTSERVICE="eval systemctl restart \$service.service"
+ STOPSERVICE="eval systemctl stop \$service.service"
+ ENABLESERVICE="eval systemctl enable \$service.service"
+ SERVICESTATUS="eval systemctl status \$service.service"
+ else
+ STARTSERVICE="eval service \$service restart"
+ STOPSERVICE="eval service \$service stop"
+ ENABLESERVICE="eval chkconfig \$service on"
+ SERVICESTATUS="eval service \$service status"
+ fi
+ APACHEUSER="apache"
+ APACHEGROUP="apache"
+ PHPFPMSERV="php-fpm"
+ INETDCFGDIR=/etc/xinetd.d
+ else
+ # Otras distribuciones.
+ :
+ fi
+ for service in apache2 httpd; do
+ [ -d /etc/$service ] && APACHECFGDIR="/etc/$service"
+ if $SERVICESTATUS &>/dev/null; then APACHESERV="$service"; fi
+ done
+ for service in dhcpd dhcpd3-server isc-dhcp-server; do
+ if $SERVICESTATUS &>/dev/null; then DHCPSERV="$service"; fi
+ done
+}
+
+
+# Comprobar auto-actualización.
+function checkAutoUpdate()
+{
+ local update=0
+
+ # Actaulizar el script si ha cambiado o no existe el original.
+ if [ $REMOTE -eq 1 ]; then
+ curl -s $RAW_URL/installer/$PROGRAMNAME -o $PROGRAMNAME
+ chmod +x $PROGRAMNAME
+ if ! diff -q $PROGRAMNAME $INSTALL_TARGET/lib/$PROGRAMNAME 2>/dev/null || ! test -f $INSTALL_TARGET/lib/$PROGRAMNAME; then
+ mv $PROGRAMNAME $INSTALL_TARGET/lib
+ update=1
+ else
+ rm -f $PROGRAMNAME
+ fi
+ else
+ if ! diff -q $PROGRAMDIR/$PROGRAMNAME $INSTALL_TARGET/lib/$PROGRAMNAME 2>/dev/null || ! test -f $INSTALL_TARGET/lib/$PROGRAMNAME; then
+ cp -a $PROGRAMDIR/$PROGRAMNAME $INSTALL_TARGET/lib
+ update=1
+ fi
+ fi
+
+ return $update
+}
+
+
+function getDateTime()
+{
+ date "+%Y%m%d-%H%M%S"
+}
+
+# Escribe a fichero y muestra por pantalla
+function echoAndLog()
+{
+ echo "$1"
+ DATETIME=`getDateTime`
+ echo "$DATETIME;$SSH_CLIENT;$1" >> $LOG_FILE
+}
+
+function errorAndLog()
+{
+ echo "ERROR: $1"
+ DATETIME=`getDateTime`
+ echo "$DATETIME;$SSH_CLIENT;ERROR: $1" >> $LOG_FILE
+}
+
+# Escribe a fichero y muestra mensaje de aviso
+function warningAndLog()
+{
+ local DATETIME=`getDateTime`
+ echo "Warning: $1"
+ echo "$DATETIME;$SSH_CLIENT;Warning: $1" >> $LOG_FILE
+}
+
+
+#####################################################################
+####### Funciones de copia de seguridad y restauración de ficheros
+#####################################################################
+
+# Hace un backup del fichero pasado por parámetro
+# deja un -last y uno para el día
+function backupFile()
+{
+ if [ $# -ne 1 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local fichero=$1
+ local fecha=`date +%Y%m%d`
+
+ if [ ! -f $fichero ]; then
+ warningAndLog "${FUNCNAME}(): file $fichero doesn't exists"
+ return 1
+ fi
+
+ echoAndLog "${FUNCNAME}(): Making $fichero back-up"
+
+ # realiza una copia de la última configuración como last
+ cp -a $fichero "${fichero}-LAST"
+
+ # si para el día no hay backup lo hace, sino no
+ if [ ! -f "${fichero}-${fecha}" ]; then
+ cp -a $fichero "${fichero}-${fecha}"
+ fi
+}
+
+# Restaura un fichero desde su copia de seguridad
+function restoreFile()
+{
+ if [ $# -ne 1 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local fichero=$1
+
+ echoAndLog "${FUNCNAME}(): restoring file $fichero"
+ if [ -f "${fichero}-LAST" ]; then
+ cp -a "$fichero-LAST" "$fichero"
+ fi
+}
+
+
+#####################################################################
+####### Funciones de acceso a base de datos
+#####################################################################
+
+# Actualizar la base datos
+function importSqlFile()
+{
+ if [ $# -ne 4 ]; then
+ errorAndLog "${FNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local dbuser="$1"
+ local dbpassword="$2"
+ local database="$3"
+ local sqlfile="$4"
+ local tmpfile=$(mktemp)
+ local mycnf=/tmp/.my.cnf.$$
+ local status
+ local APIKEY=$(php -r 'echo md5(uniqid(rand(), true));')
+ REPOKEY=$(php -r 'echo md5(uniqid(rand(), true));')
+
+ if [ ! -r $sqlfile ]; then
+ errorAndLog "${FUNCNAME}(): Unable to read $sqlfile!!"
+ return 1
+ fi
+
+ echoAndLog "${FUNCNAME}(): importing SQL file to ${database}..."
+ chmod 600 $tmpfile
+ sed -e "s/SERVERIP/$SERVERIP/g" -e "s/DBUSER/$OPENGNSYS_DB_USER/g" \
+ -e "s/DBPASSWORD/$OPENGNSYS_DB_PASSWD/g" \
+ -e "s/APIKEY/$APIKEY/g" -e "s/REPOKEY/$REPOKEY/g" $sqlfile > $tmpfile
+ # Componer fichero con credenciales de conexión.
+ touch $mycnf
+ chmod 600 $mycnf
+ cat << EOT > $mycnf
+[client]
+user=$dbuser
+password=$dbpassword
+EOT
+ # Ejecutar actualización y borrar fichero de credenciales.
+ mysql --defaults-extra-file=$mycnf --default-character-set=utf8 -D "$database" < $tmpfile
+ status=$?
+ rm -f $mycnf $tmpfile
+ if [ $status -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error importing $sqlfile in database $database"
+ return 1
+ fi
+ echoAndLog "${FUNCNAME}(): file imported to database $database"
+ return 0
+}
+
+# Comprobar configuración de MySQL y recomendar cambios necesarios.
+function checkMysqlConfig()
+{
+ if [ $# -ne 2 ]; then
+ errorAndLog "${FNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local dbuser="$1"
+ local dbpassword="$2"
+ local mycnf=/tmp/.my.cnf.$$
+
+ echoAndLog "${FUNCNAME}(): checking MySQL configuration"
+ touch $mycnf
+ cat << EOT > $mycnf
+[client]
+user=$dbuser
+password=$dbpassword
+EOT
+ # Check if scheduler is active.
+ if [ "$(mysql --defaults-extra-file=$mycnf -Nse 'SELECT @@GLOBAL.event_scheduler;')" = "OFF" ]; then
+ MYSQLCONFIG="SET GLOBAL event_scheduler = ON; "
+ fi
+ rm -f $mycnf
+
+ echoAndLog "${FUNCNAME}(): MySQL configuration has checked"
+ return 0
+}
+
+#####################################################################
+####### Funciones de instalación de paquetes
+#####################################################################
+
+# Instalar las deependencias necesarias para el actualizador.
+function installDependencies()
+{
+ local package
+
+ # Comprobar si hay que actualizar PHP 5 a PHP 7.
+ eval $UPDATEPKGLIST
+ if [ -f /etc/debian_version ]; then
+ # Basado en paquetes Deb.
+ PHP7VERSION=$(apt-cache pkgnames php7 2>/dev/null | grep -v -- - | sort | tail -1)
+ PHPFPMSERV="${PHP7VERSION}-fpm"
+ PHP5PKGS=( $(dpkg -l | awk '$2~/^php5/ {print $2}') )
+ if [ -n "$PHP5PKGS" ]; then
+ $DELETEPKGS ${PHP5PKGS[@]}
+ PHP5PKGS[0]="$PHP7VERSION"
+ INSTALLDEPS=${PHP5PKGS[@]//php5*-/${PHP7VERSION}-}
+ fi
+ fi
+ if [ "$OSDISTRIB" == "centos" ]; then
+ PHP7VERSION=$(yum list -q php7\* 2>/dev/null | awk -F. '/^php/ {print $1; exit;}')
+ PHPFPMSERV="${PHP7VERSION}-${PHPFPMSERV}"
+ PHP5PKGS=( $(yum list installed | awk '$1~/^php/ && $2~/^5\./ {sub(/\..*$/, "", $1); print $1}') )
+ if [ -n "$PHP5PKGS" ]; then
+ $DELETEPKGS ${PHP5PKGS[@]}
+ PHP5PKGS[0]="$PHP7VERSION-php"
+ INSTALLDEPS=${PHP5PKGS[@]//php-/${PHP7VERSION}-php}
+ fi
+ fi
+
+ if [ $# = 0 ]; then
+ echoAndLog "${FUNCNAME}(): no dependencies are needed"
+ else
+ while [ $# -gt 0 ]; do
+ package="${1/php/$PHP7VERSION}"
+ eval $CHECKPKG || INSTALLDEPS="$INSTALLDEPS $package"
+ shift
+ done
+ if [ -n "$INSTALLDEPS" ]; then
+ $INSTALLPKGS $INSTALLDEPS
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): cannot install some dependencies: $INSTALLDEPS"
+ return 1
+ fi
+ fi
+ fi
+}
+
+
+#####################################################################
+####### Funciones para descargar código
+#####################################################################
+
+function downloadCode()
+{
+ if [ $# -ne 1 ]; then
+ errorAndLog "${FUNCNAME}(): invalid number of parameters"
+ exit 1
+ fi
+
+ local url="$1"
+
+ echoAndLog "${FUNCNAME}(): downloading code..."
+
+ curl "${url}" -o opengnsys.zip && unzip opengnsys.zip && mv "OpenGnsys-$BRANCH" opengnsys
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error getting code from ${url}, verify your user and password"
+ return 1
+ fi
+ rm -f opengnsys.zip
+ echoAndLog "${FUNCNAME}(): code was downloaded"
+ return 0
+}
+
+
+############################################################
+### Detectar red
+############################################################
+
+# Comprobar si existe conexión.
+function checkNetworkConnection()
+{
+ OPENGNSYS_SERVER=${OPENGNSYS_SERVER:-"opengnsys.es"}
+ if which curl &>/dev/null; then
+ curl --connect-timeout 10 -s $OPENGNSYS_SERVER -o /dev/null
+ elif which wget &>/dev/null; then
+ wget --spider -q $OPENGNSYS_SERVER
+ else
+ echoAndLog "${FUNCNAME}(): Cannot execute \"wget\" nor \"curl\"."
+ return 1
+ fi
+}
+
+# Comprobar si la versión es anterior a la actual.
+function checkVersion()
+{
+ local PRE
+
+ # Obtener versión actual y versión a actualizar.
+ [ -f $INSTALL_TARGET/doc/VERSION.txt ] && OLDVERSION=$(awk '{print $2}' $INSTALL_TARGET/doc/VERSION.txt 2>/dev/null)
+ [ -f $INSTALL_TARGET/doc/VERSION.json ] && OLDVERSION=$(jq -r '.version' $INSTALL_TARGET/doc/VERSION.json 2>/dev/null)
+ if [ $REMOTE -eq 1 ]; then
+ NEWVERSION=$(curl -s $RAW_URL/doc/VERSION.json 2>/dev/null | jq -r '.version')
+ else
+ NEWVERSION=$(jq -r '.version' $PROGRAMDIR/../doc/VERSION.json 2>/dev/null)
+ fi
+ [[ "$NEWVERSION" =~ pre ]] && PRE=1
+
+ # Comparar versiones.
+ [[ "$NEWVERSION" < "${OLDVERSION/pre/}" ]] && return 1
+ [ "${NEWVERSION/pre/}" == "$OLDVERSION" -a "$PRE" == "1" ] && return 1
+
+ return 0
+}
+
+# Obtener los parámetros de red del servidor.
+function getNetworkSettings()
+{
+ # Variables globales definidas:
+ # - SERVERIP: IP local de la interfaz por defecto.
+
+ local DEVICES
+ local dev
+
+ echoAndLog "${FUNCNAME}(): Detecting network parameters"
+ SERVERIP="$ServidorAdm"
+ DEVICES="$(ip -o link show up | awk '!/loopback/ {sub(/:.*/,"",$2); print $2}')"
+ for dev in $DEVICES; do
+ [ -z "$SERVERIP" ] && SERVERIP=$(ip -o addr show dev $dev | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4)}')
+ done
+}
+
+
+#####################################################################
+####### Funciones específicas de la instalación de Opengnsys
+#####################################################################
+
+# Actualizar cliente OpenGnsys.
+function updateClientFiles()
+{
+ local ENGINECFG=$INSTALL_TARGET/client/etc/engine.cfg
+
+ # Actualizar ficheros del cliente.
+ backupFile $ENGINECFG
+ echoAndLog "${FUNCNAME}(): Updating OpenGnsys Client files"
+ rsync -irplt $WORKDIR/opengnsys/client/shared/* $INSTALL_TARGET/client
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error while updating client structure"
+ exit 1
+ fi
+
+ # Actualizar librerías del motor de clonación.
+ echoAndLog "${FUNCNAME}(): Updating OpenGnsys Cloning Engine files"
+ rsync -irplt $WORKDIR/opengnsys/client/engine/*.lib* $INSTALL_TARGET/client/lib/engine/bin
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error while updating engine files"
+ exit 1
+ fi
+ # Actualizar fichero de configuración del motor de clonación.
+ if ! grep -q "^TZ" $ENGINECFG; then
+ TZ=$(timedatectl status | awk -F"[:()]" '/Time.*zone/ {print $2}')
+ cat << EOT >> $ENGINECFG
+# OpenGnsys Server timezone.
+TZ="${TZ// /}"
+EOT
+ fi
+ if ! diff -q ${ENGINECFG}{,-LAST} &>/dev/null; then
+ NEWFILES="$NEWFILES $ENGINECFG"
+ else
+ rm -f ${ENGINECFG}-LAST
+ fi
+ # Obtener URL para descargas adicionales.
+ DOWNLOADURL=$(oglivecli config download-url 2>/dev/null)
+ DOWNLOADURL=${DOWNLOADURL:-"https://$OPENGNSYS_SERVER/trac/downloads"}
+
+ echoAndLog "${FUNCNAME}(): client files successfully updated"
+}
+
+# Configurar HTTPS y exportar usuario y grupo del servicio Apache.
+function apacheConfiguration ()
+{
+ local config template module socketfile
+
+ # Avtivar PHP-FPM.
+ echoAndLog "${FUNCNAME}(): configuring PHP-FPM"
+ service=$PHPFPMSERV
+ $ENABLESERVICE; $STARTSERVICE
+
+ # Activar módulos de Apache.
+ if [ -e $APACHECFGDIR/sites-available/opengnsys.conf ]; then
+ echoAndLog "${FUNCNAME}(): Configuring Apache modules"
+ a2ensite default-ssl
+ for module in $APACHEENABLEMODS; do a2enmod -q "$module"; done
+ for module in $APACHEDISABLEMODS; do a2dismod -q "${module//PHP7VERSION}"; done
+ a2ensite opengnsys
+ elif [ -e $APACHECFGDIR/conf.modules.d ]; then
+ echoAndLog "${FUNCNAME}(): Configuring Apache modules"
+ sed -i '/rewrite/s/^#//' $APACHECFGDIR/*.conf
+ fi
+ # Habilitar nueva web.
+ if [ ! -e $APACHECFGDIR/sites-available/opengnsys3.conf ]; then
+ sed -e "s,CONSOLEDIR3,$INSTALL_TARGET/www3,g" \
+ $WORKDIR/opengnsys/server/etc/apache-console3.conf.tmpl > $APACHECFGDIR/sites-available/opengnsys3.conf
+ a2dissite opengnsys
+ a2ensite opengnsys3
+ fi
+ # Elegir plantilla según versión de Apache.
+ if [ -n "$(apachectl -v | grep "2\.[0-2]")" ]; then
+ template=$WORKDIR/opengnsys/server/etc/apache-prev2.4.conf.tmpl > $config
+ else
+ template=$WORKDIR/opengnsys/server/etc/apache.conf.tmpl
+ fi
+ sockfile=$(find /run/php -name "php*.sock" -type s -print 2>/dev/null | tail -1)
+ # Actualizar configuración de Apache a partir de fichero de plantilla.
+ for config in $APACHECFGDIR/{,sites-available/}opengnsys.conf; do
+ if [ -e $config ]; then
+ if [ -n "$sockfile" ]; then
+ sed -e "s,CONSOLEDIR,$INSTALL_TARGET/www,g; s,proxy:fcgi:.*,proxy:unix:${sockfile%% *}|fcgi://localhost\",g" $template > $config
+ else
+ sed -e "s,CONSOLEDIR,$INSTALL_TARGET/www,g" $template > $config
+ fi
+ fi
+ done
+
+ # Reiniciar Apache.
+ service=$APACHESERV; $STARTSERVICE
+
+ # Variables de ejecución de Apache.
+ # - APACHE_RUN_USER
+ # - APACHE_RUN_GROUP
+ if [ -f $APACHECFGDIR/envvars ]; then
+ source $APACHECFGDIR/envvars
+ fi
+ APACHE_RUN_USER=${APACHE_RUN_USER:-"$APACHEUSER"}
+ APACHE_RUN_GROUP=${APACHE_RUN_GROUP:-"$APACHEGROUP"}
+}
+
+# Configurar servicio Rsync.
+function rsyncConfigure()
+{
+ local service
+
+ # Configurar acceso a Rsync.
+ if [ ! -f /etc/rsyncd.conf ]; then
+ echoAndLog "${FUNCNAME}(): Configuring Rsync service"
+ NEWFILES="$NEWFILES /etc/rsyncd.conf"
+ sed -e "s/CLIENTUSER/$OPENGNSYS_CLIENTUSER/g" \
+ $WORKDIR/opengnsys/repoman/etc/rsyncd.conf.tmpl > /etc/rsyncd.conf
+ # Habilitar Rsync.
+ if [ -f /etc/default/rsync ]; then
+ perl -pi -e 's/RSYNC_ENABLE=.*/RSYNC_ENABLE=inetd/' /etc/default/rsync
+ fi
+ if [ -f $INETDCFGDIR/rsync ]; then
+ perl -pi -e 's/disable.*/disable = no/' $INETDCFGDIR/rsync
+ else
+ cat << EOT > $INETDCFGDIR/rsync
+service rsync
+{
+ disable = no
+ socket_type = stream
+ wait = no
+ user = root
+ server = $(which rsync)
+ server_args = --daemon
+ log_on_failure += USERID
+ flags = IPv6
+}
+EOT
+ fi
+ # Activar e iniciar Rsync.
+ service="rsync" $ENABLESERVICE
+ service="xinetd"
+ $ENABLESERVICE; $STARTSERVICE
+ fi
+}
+
+# Copiar ficheros del OpenGnsys Web Console.
+function updateWebFiles()
+{
+ local ERRCODE COMPATDIR f
+
+ echoAndLog "${FUNCNAME}(): Updating web files..."
+
+ # Copiar los ficheros nuevos conservando el archivo de configuración de acceso.
+ backupFile $INSTALL_TARGET/www/controlacceso.php
+ mv $INSTALL_TARGET/www $INSTALL_TARGET/WebConsole
+ rsync -irplt $WORKDIR/opengnsys/admin/WebConsole $INSTALL_TARGET
+ ERRCODE=$?
+ mv $INSTALL_TARGET/WebConsole $INSTALL_TARGET/www
+ rm -fr $INSTALL_TARGET/www/xajax
+ unzip -o $WORKDIR/opengnsys/admin/slim-2.6.1.zip -d $INSTALL_TARGET/www/rest
+ unzip -o $WORKDIR/opengnsys/admin/swagger-ui-2.2.5.zip -d $INSTALL_TARGET/www/rest
+ if [ $ERRCODE != 0 ]; then
+ errorAndLog "${FUNCNAME}(): Error updating web files."
+ exit 1
+ fi
+ restoreFile $INSTALL_TARGET/www/controlacceso.php
+
+ # Cambiar acceso a protocolo HTTPS.
+ if grep -q "http://" $INSTALL_TARGET/www/controlacceso.php 2>/dev/null; then
+ echoAndLog "${FUNCNAME}(): updating web access file"
+ perl -pi -e 's!http://!https://!g' $INSTALL_TARGET/www/controlacceso.php
+ NEWFILES="$NEWFILES $INSTALL_TARGET/www/controlacceso.php"
+ fi
+
+ # Compatibilidad con dispositivos móviles.
+ COMPATDIR="$INSTALL_TARGET/www/principal"
+ for f in acciones administracion aula aulas hardwares imagenes menus repositorios softwares; do
+ sed 's/clickcontextualnodo/clicksupnodo/g' $COMPATDIR/$f.php > $COMPATDIR/$f.device.php
+ done
+ cp -a $COMPATDIR/imagenes.device.php $COMPATDIR/imagenes.device4.php
+ # Acceso al manual de usuario
+ ln -fs ../doc/userManual $INSTALL_TARGET/www/userManual
+ # Fichero de log de la API REST.
+ touch $INSTALL_TARGET/log/{ogagent,rest,remotepc}.log
+
+ echoAndLog "${FUNCNAME}(): Web files successfully updated"
+}
+
+# Instalar dependencias y copiar ficheros de la nueva web de OpenGnsys 3.
+function updateWeb3()
+{
+ echoAndLog "${FUNCNAME}(): Installing OpenGnsys 3 Web Console..."
+ # Copiar ficheros.
+ mkdir -p $INSTALL_TARGET/www3
+ cp -a $WORKDIR/opengnsys/admin/WebConsole3/backend $INSTALL_TARGET/www3
+
+ # Instalar Composer.
+ if [ ! -f /usr/local/bin/composer.phar ]; then
+ php -r "copy('https://getcomposer.org/installer', '/tmp/composer-setup.php');"
+ php /tmp/composer-setup.php --install-dir=/usr/local/bin
+ rm -f /tmp/composer-setup.php
+ fi
+ # Instalar dependencias y migrar la BD para el backend.
+ pushd $INSTALL_TARGET/www3/backend
+ composer.phar update
+ chmod 777 -R var/cache var/logs
+ echo "Enter MySQL root password: "
+ mysql -u root -p <<< "
+ CREATE DATABASE IF NOT EXISTS ${OPENGNSYS_DATABASE}3;
+ GRANT ALL PRIVILEGES ON ${OPENGNSYS_DATABASE}3.* TO $OPENGNSYS_DBUSER IDENTIFIED BY '$OPENGNSYS_DBPASSWORD';
+"
+ # Crear la base de datos
+ php app/console doctrine:database:create --if-not-exists
+ # Actualizar el esquema de la base de datos
+ php app/console doctrine:schema:update --force
+ php app/console doctrine:fixtures:load
+ # Crear el usuario con permisos de Administrador
+ php app/console fos:user:create admin admin@localhost.localdomain admin
+ # Crear el cliente Auth2 para obtener us client_id y secret
+ php app/console opengnsys:oauth-server:client:create --grant-type="password" --grant-type="refresh_token" --grant-type="token" --grant-type="http://opengnsys.es/grants/og_client"
+ # Realizar la migración de la versión anterior de opengnsys 1.1
+ php app/console opengnsys:migration:execute
+ popd
+
+ # Instalar NodeJs y NG.
+ curl -sL https://deb.nodesource.com/setup_10.x | bash -
+ apt install nodejs
+ [ -L /usr/bin/node ] || ln -s /usr/bin/nodejs /usr/bin/node
+ npm install -g @angular/cli@6.2.3
+ # Instalar el frontend.
+ pushd $WORKDIR/opengnsys/admin/WebConsole3/frontend
+ npm install
+ sed -i "s/SERVERIP/$SERVERIP/" src/environments/environment.ts
+ sed -i 's,base href=.*,base href="/opengnsys3/frontend/">,' src/index.html
+ ng build
+ rsync -irplt dist/opengnsysAngular6/* $INSTALL_TARGET/www3/frontend
+ popd
+}
+
+# Copiar ficheros en la zona de descargas de OpenGnsys Web Console.
+function updateDownloadableFiles()
+{
+ local FILENAME=ogagentpkgs-$NEWVERSION.tar.gz
+ local TARGETFILE=$WORKDIR/$FILENAME
+
+ # Descargar archivo comprimido, si es necesario.
+ if [ -s $PROGRAMDIR/$FILENAME ]; then
+ echoAndLog "${FUNCNAME}(): Moving $PROGRAMDIR/$FILENAME file to $(dirname $TARGETFILE)"
+ mv $PROGRAMDIR/$FILENAME $TARGETFILE
+ else
+ echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
+ curl $DOWNLOADURL/$FILENAME -o $TARGETFILE
+ fi
+ if [ ! -s $TARGETFILE ]; then
+ errorAndLog "${FUNCNAME}(): Cannot download $FILENAME"
+ return 1
+ fi
+
+ # Descomprimir fichero en zona de descargas.
+ tar xvzf $TARGETFILE -C $INSTALL_TARGET/www/descargas
+ if [ $? != 0 ]; then
+ errorAndLog "${FUNCNAME}(): Error uncompressing archive $FILENAME"
+ return 1
+ fi
+}
+
+# Copiar carpeta de Interface
+function updateInterfaceAdm()
+{
+ local errcode=0
+
+ # Crear carpeta y copiar Interface
+ echoAndLog "${FUNCNAME}(): Copying Administration Interface Folder"
+ mv $INSTALL_TARGET/client/interfaceAdm $INSTALL_TARGET/client/Interface
+ rsync -irplt $WORKDIR/opengnsys/admin/Interface $INSTALL_TARGET/client
+ errcoce=$?
+ mv $INSTALL_TARGET/client/Interface $INSTALL_TARGET/client/interfaceAdm
+ if [ $errcode -ne 0 ]; then
+ echoAndLog "${FUNCNAME}(): error while updating admin interface"
+ exit 1
+ fi
+ echoAndLog "${FUNCNAME}(): Admin interface successfully updated"
+}
+
+# Crear documentación Doxygen para la consola web.
+function makeDoxygenFiles()
+{
+ echoAndLog "${FUNCNAME}(): Making Doxygen web files..."
+ $WORKDIR/opengnsys/installer/ogGenerateDoc.sh \
+ $WORKDIR/opengnsys/client/engine $INSTALL_TARGET/www
+ if [ ! -d "$INSTALL_TARGET/www/html" ]; then
+ errorAndLog "${FUNCNAME}(): unable to create Doxygen web files"
+ return 1
+ fi
+ rm -fr "$INSTALL_TARGET/www/api"
+ mv "$INSTALL_TARGET/www/html" "$INSTALL_TARGET/www/api"
+ rm -fr $INSTALL_TARGET/www/{man,perlmod,rtf}
+ echoAndLog "${FUNCNAME}(): Doxygen web files created successfully"
+}
+
+
+# Crea la estructura base de la instalación de opengnsys
+function createDirs()
+{
+ # Crear estructura de directorios.
+ echoAndLog "${FUNCNAME}(): creating directory paths in ${INSTALL_TARGET}"
+ local dir
+
+ mkdir -p ${INSTALL_TARGET}/{bin,doc,etc,lib,sbin,www}
+ mkdir -p ${INSTALL_TARGET}/{client,images/groups}
+ mkdir -p ${INSTALL_TARGET}/log/clients
+ ln -fs ${INSTALL_TARGET}/log /var/log/opengnsys
+ # Detectar directorio de instalación de TFTP.
+ if [ ! -L ${INSTALL_TARGET}/tftpboot ]; then
+ for dir in /var/lib/tftpboot /srv/tftp; do
+ [ -d $dir ] && ln -fs $dir ${INSTALL_TARGET}/tftpboot
+ done
+ fi
+ mkdir -p $INSTALL_TARGET/tftpboot/menu.lst/examples
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error while creating dirs. Do you have write permissions?"
+ return 1
+ fi
+ ! [ -f $INSTALL_TARGET/tftpboot/menu.lst/templates/00unknown ] && mv $INSTALL_TARGET/tftpboot/menu.lst/templates/* $INSTALL_TARGET/tftpboot/menu.lst/examples
+
+ # Crear usuario ficticio.
+ if id -u $OPENGNSYS_CLIENTUSER &>/dev/null; then
+ echoAndLog "${FUNCNAME}(): user \"$OPENGNSYS_CLIENTUSER\" is already created"
+ else
+ echoAndLog "${FUNCNAME}(): creating OpenGnsys user"
+ useradd $OPENGNSYS_CLIENTUSER 2>/dev/null
+ if [ $? -ne 0 ]; then
+ errorAndLog "${FUNCNAME}(): error creating OpenGnsys user"
+ return 1
+ fi
+ fi
+
+ # Mover el fichero de registro al directorio de logs.
+ echoAndLog "${FUNCNAME}(): moving update log file"
+ mv $LOG_FILE $OGLOGFILE && LOG_FILE=$OGLOGFILE
+ chmod 600 $LOG_FILE
+
+ echoAndLog "${FUNCNAME}(): directory paths created"
+ return 0
+}
+
+# Actualización incremental de la BD (versión actaul a actaul+1, hasta final-1 a final).
+function updateDatabase()
+{
+ local DBDIR="$WORKDIR/opengnsys/admin/Database"
+ local file FILES=""
+
+ echoAndLog "${FUNCNAME}(): looking for database updates"
+ pushd $DBDIR >/dev/null
+ # Bucle de actualización incremental desde versión actual a la final.
+ for file in $OPENGNSYS_DATABASE-*-*.sql; do
+ case "$file" in
+ $OPENGNSYS_DATABASE-$OLDVERSION-$NEWVERSION.sql)
+ # Actualización única de versión inicial y final.
+ FILES="$FILES $file"
+ break
+ ;;
+ $OPENGNSYS_DATABASE-*-postinst.sql)
+ # Ignorar fichero específico de post-instalación.
+ ;;
+ $OPENGNSYS_DATABASE-$OLDVERSION-*.sql)
+ # Actualización de versión n a n+1.
+ FILES="$FILES $file"
+ OLDVERSION="$(echo $file | cut -f3 -d-)"
+ ;;
+ $OPENGNSYS_DATABASE-*-$NEWVERSION.sql)
+ # Última actualización de versión final-1 a final.
+ if [ -n "$FILES" ]; then
+ FILES="$FILES $file"
+ break
+ fi
+ ;;
+ esac
+ done
+ # Aplicar posible actualización propia para la versión final.
+ file=$OPENGNSYS_DATABASE-$NEWVERSION.sql
+ if [ -n "$FILES" -o "$OLDVERSION" = "$NEWVERSION" -a -r $file ]; then
+ FILES="$FILES $file"
+ fi
+
+ popd >/dev/null
+ if [ -n "$FILES" ]; then
+ for file in $FILES; do
+ importSqlFile $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD $OPENGNSYS_DATABASE $DBDIR/$file
+ done
+ echoAndLog "${FUNCNAME}(): database is update"
+ else
+ echoAndLog "${FUNCNAME}(): database unchanged"
+ fi
+}
+
+# Copia ficheros de configuración y ejecutables genéricos del servidor.
+function updateServerFiles()
+{
+ # No copiar ficheros del antiguo cliente Initrd
+ local SOURCES=( repoman/bin \
+ server/bin \
+ server/lib \
+ admin/Sources/Services/ogAdmServerAux \
+ admin/Sources/Services/ogAdmRepoAux \
+ server/tftpboot \
+ installer/opengnsys_uninstall.sh \
+ installer/opengnsys_export.sh \
+ installer/opengnsys_import.sh \
+ doc )
+ local TARGETS=( bin \
+ bin \
+ lib \
+ sbin/ogAdmServerAux \
+ sbin/ogAdmRepoAux \
+ tftpboot \
+ lib/opengnsys_uninstall.sh \
+ lib/opengnsys_export.sh \
+ lib/opengnsys_import.sh \
+ doc )
+
+ if [ ${#SOURCES[@]} != ${#TARGETS[@]} ]; then
+ errorAndLog "${FUNCNAME}(): inconsistent number of array items"
+ exit 1
+ fi
+
+ echoAndLog "${FUNCNAME}(): updating files in server directories"
+ pushd $WORKDIR/opengnsys >/dev/null
+ local i
+ for (( i = 0; i < ${#SOURCES[@]}; i++ )); do
+ if [ -d "$INSTALL_TARGET/${TARGETS[i]}" ]; then
+ rsync -irplt "${SOURCES[i]}" $(dirname $(readlink -e "$INSTALL_TARGET/${TARGETS[i]}"))
+ else
+ rsync -irplt "${SOURCES[i]}" $(readlink -m "$INSTALL_TARGET/${TARGETS[i]}")
+ fi
+ done
+ popd >/dev/null
+ NEWFILES="" # Ficheros de configuración que han cambiado de formato.
+ if grep -q 'pxelinux.0' /etc/dhcp*/dhcpd*.conf; then
+ echoAndLog "${FUNCNAME}(): updating DHCP files"
+ perl -pi -e 's/pxelinux.0/grldr/' /etc/dhcp*/dhcpd*.conf
+ service=$DHCPSERV; $STARTSERVICE
+ NEWFILES="/etc/dhcp*/dhcpd*.conf"
+ fi
+ if ! diff -q $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys 2>/dev/null; then
+ echoAndLog "${FUNCNAME}(): updating new init file"
+ backupFile /etc/init.d/opengnsys
+ cp -a $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.init /etc/init.d/opengnsys
+ NEWFILES="$NEWFILES /etc/init.d/opengnsys"
+ fi
+ if ! diff -q $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default /etc/default/opengnsys >/dev/null; then
+ echoAndLog "${FUNCNAME}(): updating new default file"
+ backupFile /etc/default/opengnsys
+ # Buscar si hay nuevos parámetros.
+ local var valor
+ while IFS="=" read -e var valor; do
+ [[ $var =~ ^# ]] || \
+ grep -q "^$var=" /etc/default/opengnsys || \
+ echo "$var=$valor" >> /etc/default/opengnsys
+ done < $WORKDIR/opengnsys/admin/Sources/Services/opengnsys.default
+ NEWFILES="$NEWFILES /etc/default/opengnsys"
+ fi
+ if egrep -q "(UrlMsg=.*msgbrowser.php)|(UrlMenu=http://)" $INSTALL_TARGET/client/etc/ogAdmClient.cfg 2>/dev/null; then
+ echoAndLog "${FUNCNAME}(): updating new client config file"
+ backupFile $INSTALL_TARGET/client/etc/ogAdmClient.cfg
+ perl -pi -e 's!UrlMsg=.*msgbrowser\.php!UrlMsg=http://localhost/cgi-bin/httpd-log\.sh!g; s!UrlMenu=http://!UrlMenu=https://!g' $INSTALL_TARGET/client/etc/ogAdmClient.cfg
+ NEWFILES="$NEWFILES $INSTALL_TARGET/client/etc/ogAdmClient.cfg"
+ fi
+
+ echoAndLog "${FUNCNAME}(): updating cron files"
+ [ ! -f /etc/cron.d/opengnsys ] && echo "* * * * * root [ -x $INSTALL_TARGET/bin/opengnsys.cron ] && $INSTALL_TARGET/bin/opengnsys.cron" > /etc/cron.d/opengnsys
+ [ ! -f /etc/cron.d/torrentcreator ] && echo "* * * * * root [ -x $INSTALL_TARGET/bin/torrent-creator ] && $INSTALL_TARGET/bin/torrent-creator" > /etc/cron.d/torrentcreator
+ [ ! -f /etc/cron.d/torrenttracker ] && echo "5 * * * * root [ -x $INSTALL_TARGET/bin/torrent-tracker ] && $INSTALL_TARGET/bin/torrent-tracker" > /etc/cron.d/torrenttracker
+ [ ! -f /etc/cron.d/imagedelete ] && echo "* * * * * root [ -x $INSTALL_TARGET/bin/deletepreimage ] && $INSTALL_TARGET/bin/deletepreimage" > /etc/cron.d/imagedelete
+ [ ! -f /etc/cron.d/ogagentqueue ] && echo "* * * * * root [ -x $INSTALL_TARGET/bin/ogagentqueue.cron ] && $INSTALL_TARGET/bin/ogagentqueue.cron" > /etc/cron.d/ogagentqueue
+ echoAndLog "${FUNCNAME}(): server files successfully updated"
+}
+
+####################################################################
+### Funciones de compilación de código fuente de servicios
+####################################################################
+
+# Mueve el fichero del nuevo servicio si es distinto al del directorio destino.
+function moveNewService()
+{
+ local service
+
+ # Recibe 2 parámetros: fichero origen y directorio destino.
+ [ $# == 2 ] || return 1
+ [ -f $1 -a -d $2 ] || return 1
+
+ # Comparar los ficheros.
+ if ! diff -q $1 $2/$(basename $1) &>/dev/null; then
+ # Parar los servicios si fuese necesario.
+ [ -z "$NEWSERVICES" ] && service="opengnsys" $STOPSERVICE
+ # Nuevo servicio.
+ NEWSERVICES="$NEWSERVICES $(basename $1)"
+ # Mover el nuevo fichero de servicio
+ mv $1 $2
+ fi
+}
+
+
+# Recompilar y actualiza los serivicios y clientes.
+function compileServices()
+{
+ local hayErrores=0
+
+ # Compilar OpenGnsys Server
+ echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Admin Server"
+ pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmServer
+ make && moveNewService ogAdmServer $INSTALL_TARGET/sbin
+ if [ $? -ne 0 ]; then
+ echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Admin Server"
+ hayErrores=1
+ fi
+ popd
+ # Parar antiguo servicio de repositorio y añadir clave de acceso REST en su fichero de configuración.
+ pgrep ogAdmRepo > /dev/null && service="ogAdmRepo" $STOPSERVICE
+ grep -q '^ApiToken=' $INSTALL_TARGET/etc/ogAdmRepo.cfg && \
+ sed -i "s/^ApiToken=.*$/ApiToken=$REPOKEY/" $INSTALL_TARGET/etc/ogAdmRepo.cfg || \
+ sed -i "$ a\ApiToken=$REPOKEY/" $INSTALL_TARGET/etc/ogAdmRepo.cfg
+ # Compilar OpenGnsys Agent
+ echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Server Agent"
+ pushd $WORKDIR/opengnsys/admin/Sources/Services/ogAdmAgent
+ make && moveNewService ogAdmAgent $INSTALL_TARGET/sbin
+ if [ $? -ne 0 ]; then
+ echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Server Agent"
+ hayErrores=1
+ fi
+ popd
+
+ # Compilar OpenGnsys Client
+ echoAndLog "${FUNCNAME}(): Recompiling OpenGnsys Client"
+ pushd $WORKDIR/opengnsys/admin/Sources/Clients/ogAdmClient
+ make && mv ogAdmClient $INSTALL_TARGET/client/bin
+ if [ $? -ne 0 ]; then
+ echoAndLog "${FUNCNAME}(): error while compiling OpenGnsys Client"
+ hayErrores=1
+ fi
+ popd
+
+ return $hayErrores
+}
+
+
+####################################################################
+### Funciones instalacion cliente OpenGnsys
+####################################################################
+
+# Actualizar cliente OpenGnsys
+function updateClient()
+{
+ #local FILENAME=ogLive-precise-3.2.0-23-generic-r5159.iso # 1.1.0-rc6 (old)
+ local FILENAME=ogLive-xenial-4.13.0-17-generic-amd64-r5520.iso # 1.1.0-rc6
+ local SOURCEFILE=$DOWNLOADURL/$FILENAME
+ local TARGETFILE=$(oglivecli config download-dir)/$FILENAME
+ local SOURCELENGTH
+ local TARGETLENGTH
+ local OGINITRD
+ local SAMBAPASS
+
+ # Comprobar si debe convertirse el antiguo cliente al nuevo formato ogLive.
+ if oglivecli check | grep -q "oglivecli convert"; then
+ echoAndLog "${FUNCNAME}(): Converting OpenGnsys Client to default ogLive"
+ oglivecli convert
+ fi
+ # Comprobar si debe actualizarse el cliente.
+ SOURCELENGTH=$(curl -sI $SOURCEFILE 2>&1 | awk '/Content-Length:/ {gsub("\r", ""); print $2}')
+ TARGETLENGTH=$(stat -c "%s" $TARGETFILE 2>/dev/null)
+ [ -z $TARGETLENGTH ] && TARGETLENGTH=0
+ if [ "$SOURCELENGTH" != "$TARGETLENGTH" ]; then
+ echoAndLog "${FUNCNAME}(): Downloading $FILENAME"
+ oglivecli download $FILENAME
+ if [ ! -s $TARGETFILE ]; then
+ errorAndLog "${FUNCNAME}(): Error downloading $FILENAME"
+ return 1
+ fi
+ # Actaulizar la imagen ISO del ogclient.
+ echoAndLog "${FUNCNAME}(): Updatting ogLive client"
+ oglivecli install $FILENAME
+
+ CLIENTUPDATED=${FILENAME%.*}
+
+ echoAndLog "${FUNCNAME}(): ogLive successfully updated"
+ else
+ # Si no existe, crear el fichero de claves de Rsync.
+ if [ ! -f /etc/rsyncd.secrets ]; then
+ echoAndLog "${FUNCNAME}(): Restoring ogLive access key"
+ OGINITRD=$(oglivecli config install-dir)/$(jq -r ".oglive[.default].directory")/oginitrd.img
+ SAMBAPASS=$(gzip -dc $OGINITRD | \
+ cpio -i --to-stdout scripts/ogfunctions 2>&1 | \
+ grep "^[ ].*OPTIONS=" | \
+ sed 's/\(.*\)pass=\(\w*\)\(.*\)/\2/')
+ echo -ne "$SAMBAPASS\n$SAMBAPASS\n" | setsmbpass
+ else
+ echoAndLog "${FUNCNAME}(): ogLive is already updated"
+ fi
+ # Versión del ogLive instalado.
+ echo "${FILENAME%.*}" > $INSTALL_TARGET/doc/veroglive.txt
+ fi
+}
+
+# Comprobar permisos y ficheros.
+function checkFiles()
+{
+ local LOGROTATEDIR=/etc/logrotate.d
+
+ # Comprobar permisos adecuados.
+ if [ -x $INSTALL_TARGET/bin/checkperms ]; then
+ echoAndLog "${FUNCNAME}(): Checking permissions"
+ OPENGNSYS_DIR="$INSTALL_TARGET" OPENGNSYS_USER="$OPENGNSYS_CLIENTUSER" APACHE_USER="$APACHE_RUN_USER" APACHE_GROUP="$APACHE_RUN_GROUP" $INSTALL_TARGET/bin/checkperms
+ fi
+ # Eliminamos el fichero de estado del tracker porque es incompatible entre los distintos paquetes
+ if [ -f /tmp/dstate ]; then
+ echoAndLog "${FUNCNAME}(): Deleting unused files"
+ rm -f /tmp/dstate
+ fi
+ # Crear nuevos ficheros de logrotate y borrar el fichero antiguo.
+ if [ -d $LOGROTATEDIR ]; then
+ rm -f $LOGROTATEDIR/opengnsys
+ if [ ! -f $LOGROTATEDIR/opengnsysServer ]; then
+ echoAndLog "${FUNCNAME}(): Creating logrotate configuration file for server"
+ sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
+ $WORKDIR/opengnsys/server/etc/logrotate.tmpl > $LOGROTATEDIR/opengnsysServer
+ fi
+ if [ ! -f $LOGROTATEDIR/opengnsysRepo ]; then
+ echoAndLog "${FUNCNAME}(): Creating logrotate configuration file for repository"
+ sed -e "s/OPENGNSYSDIR/${INSTALL_TARGET//\//\\/}/g" \
+ $WORKDIR/opengnsys/server/etc/logrotate.tmpl > $LOGROTATEDIR/opengnsysRepo
+ fi
+ fi
+}
+
+# Resumen de actualización.
+function updateSummary()
+{
+ # Actualizar fichero de versión y revisión.
+ local VERSIONFILE REVISION
+ VERSIONFILE="$INSTALL_TARGET/doc/VERSION.json"
+ # Obtener revisión.
+ if [ $REMOTE -eq 1 ]; then
+ # Revisión: rAñoMesDía.Gitcommit (8 caracteres de fecha y 7 primeros de commit).
+ REVISION=$(curl -s "$API_URL" | jq '"r" + (.commit.commit.committer.date | split("-") | join("")[:8]) + "." + (.commit.sha[:7])')
+ else
+ # Parámetro "release" del fichero JSON.
+ REVISION=$(jq -r '.release' $PROGRAMDIR/../doc/VERSION.json 2>/dev/null)
+ fi
+ [ -f $VERSIONFILE ] || echo '{ "project": "OpenGnsys" }' > $VERSIONFILE
+ jq ".release=$REVISION" $VERSIONFILE | sponge $VERSIONFILE
+ VERSION="$(jq -r '[.project, .version, .codename, .release] | join(" ")' $VERSIONFILE 2>/dev/null)"
+ # Borrar antiguo fichero de versión.
+ rm -f "${VERSIONFILE/json/txt}"
+
+ echo
+ echoAndLog "OpenGnsys Update Summary"
+ echo "========================"
+ echoAndLog "Project version: $VERSION"
+ echoAndLog "Update log file: $LOG_FILE"
+ if [ -n "$NEWFILES" ]; then
+ echoAndLog "Check new config files: $(echo $NEWFILES)"
+ fi
+ if [ -n "$NEWSERVICES" ]; then
+ echoAndLog "New compiled services: $(echo $NEWSERVICES)"
+ # Indicar si se debe reiniciar servicios manualmente o usando el Cron.
+ [ -f /etc/default/opengnsys ] && source /etc/default/opengnsys
+ if [ "$RUN_CRONJOB" == "no" ]; then
+ echoAndLog " WARNING: you must to restart OpenGnsys services manually"
+ else
+ echoAndLog " New OpenGnsys services will be restarted by the cronjob"
+ fi
+ fi
+ echoAndLog "Warnings:"
+ echoAndLog " - You must to clear web browser cache before loading OpenGnsys page"
+ echoAndLog " - Generated new key to access Repository REST API (file ogAdmRepo.cfg)"
+ if [ -n "$CLIENTUPDATED" ]; then
+ echoAndLog " - ogLive Client is updated to: $CLIENTUPDATED"
+ fi
+ if [ -n "$MYSQLCONFIG" ]; then
+ echoAndLog " - MySQL must be reconfigured, run next code as DB root user and restart service:"
+ echoAndLog " $MYSQLCONFIG"
+ fi
+ echo
+}
+
+
+
+#####################################################################
+####### Proceso de actualización de OpenGnsys
+#####################################################################
+
+
+echoAndLog "OpenGnsys update begins at $(date)"
+
+pushd $WORKDIR
+
+# Comprobar si hay conexión y detectar parámetros de red por defecto.
+checkNetworkConnection
+if [ $? -ne 0 ]; then
+ errorAndLog "Error connecting to server. Causes:"
+ errorAndLog " - Network is unreachable, check device parameters"
+ errorAndLog " - You are inside a private network, configure the proxy service"
+ errorAndLog " - Server is temporally down, try again later"
+ exit 1
+fi
+getNetworkSettings
+
+# Comprobar si se intanta actualizar a una versión anterior.
+checkVersion
+if [ $? -ne 0 ]; then
+ errorAndLog "Cannot downgrade to an older version ($OLDVERSION to $NEWVERSION)"
+ errorAndLog "You must to uninstall OpenGnsys and install desired release"
+ exit 1
+fi
+
+# Comprobar auto-actualización del programa.
+if [ "$PROGRAMDIR" != "$INSTALL_TARGET/bin" ]; then
+ checkAutoUpdate
+ if [ $? -ne 0 ]; then
+ echoAndLog "OpenGnsys updater has been overwritten"
+ echoAndLog "Please, rerun this script"
+ exit
+ fi
+fi
+
+# Detectar datos de auto-configuración del instalador.
+autoConfigure
+
+# Instalar dependencias.
+installDependencies ${DEPENDENCIES[*]}
+if [ $? -ne 0 ]; then
+ errorAndLog "Error: you must to install all needed dependencies"
+ exit 1
+fi
+
+# Arbol de directorios de OpenGnsys.
+createDirs ${INSTALL_TARGET}
+if [ $? -ne 0 ]; then
+ errorAndLog "Error while creating directory paths"
+ exit 1
+fi
+
+# Si es necesario, descarga el repositorio de código en directorio temporal
+if [ $REMOTE -eq 1 ]; then
+ downloadCode $CODE_URL
+ if [ $? -ne 0 ]; then
+ errorAndLog "Error while getting code from repository"
+ exit 1
+ fi
+else
+ ln -fs "$(dirname $PROGRAMDIR)" opengnsys
+fi
+
+# Comprobar configuración de MySQL.
+checkMysqlConfig $OPENGNSYS_DBUSER $OPENGNSYS_DBPASSWORD
+
+# Actualizar la BD.
+updateDatabase
+
+# Actualizar ficheros complementarios del servidor
+updateServerFiles
+if [ $? -ne 0 ]; then
+ errorAndLog "Error updating OpenGnsys Server files"
+ exit 1
+fi
+
+# Configurar Rsync.
+rsyncConfigure
+
+# Actualizar ficheros del cliente
+updateClientFiles
+updateInterfaceAdm
+
+# Actualizar antigua páqina web
+apacheConfiguration
+updateWebFiles
+if [ $? -ne 0 ]; then
+ errorAndLog "Error updating OpenGnsys Web Admin files"
+ exit 1
+fi
+# Actualizar nueva página web
+updateWeb3
+
+# Actaulizar ficheros descargables.
+updateDownloadableFiles
+# Generar páginas Doxygen para instalar en el web
+makeDoxygenFiles
+
+# Recompilar y actualizar los servicios del sistema
+compileServices
+
+# Actaulizar ficheros auxiliares del cliente
+updateClient
+if [ $? -ne 0 ]; then
+ errorAndLog "Error updating client files"
+ exit 1
+fi
+
+# Comprobar permisos y ficheros.
+checkFiles
+
+# Mostrar resumen de actualización.
+updateSummary
+
+rm -rf $WORKDIR
+echoAndLog "OpenGnsys update finished at $(date)"
+
+popd
+
diff --git a/installer/vagrant/Vagrantfile-webconsole3-vbox b/installer/vagrant/Vagrantfile-webconsole3-vbox
index 3f305c95..424650ff 100644
--- a/installer/vagrant/Vagrantfile-webconsole3-vbox
+++ b/installer/vagrant/Vagrantfile-webconsole3-vbox
@@ -50,8 +50,8 @@ apt-get install -y xfce4 gnome-icon-theme-full tango-icon-theme linux-headers-$(
echo "allowed_users=anybody" > /etc/X11/Xwrapper.config
# Install OpenGnsys Server
tar xpvzf /vagrant/opengnsys3.tar.gz -C /tmp
-/tmp/opengnsys/installer/opengnsys_installer.sh
-echo y | /opt/opengnsys/bin/setserveraddr eth1
+/tmp/opengnsys/installer/opengnsys_installer3.sh
+echo y | /opt/opengnsys/bin/setserveraddr3 eth1
# Configure the virtual lab.
read -e APIID APISECRET <<<$(/opt/opengnsys/www3/backend/app/console doctrine:query:sql "SELECT random_id, secret FROM og_core__clients WHERE id=1;" | awk -F\\" '$2~/^(random_id|secret)$/ {getline; printf("%s ", $2)}')
rm -fr /opt/opengnsys/www3/backend/var/cache/*
diff --git a/server/bin/checkperms b/server/bin/checkperms
index ca9e1d7d..c02b3350 100755
--- a/server/bin/checkperms
+++ b/server/bin/checkperms
@@ -57,5 +57,5 @@ chown -R $APACHE_USER:$APACHE_GROUP $OPENGNSYS_DIR/tftpboot/menu.lst
chown -R :$OPENGNSYS_USER $OPENGNSYS_DIR/tftpboot/ogLive*
find -L $OPENGNSYS_DIR/tftpboot -type d -exec chmod 755 {} \;
find -L $OPENGNSYS_DIR/tftpboot -type f -exec chmod 644 {} \;
-#chown $APACHE_USER:$APACHE_GROUP $OPENGNSYS_DIR/log/{ogagent,remotepc,rest}.log
+chown $APACHE_USER:$APACHE_GROUP $OPENGNSYS_DIR/log/{ogagent,remotepc,rest}.log 2>/dev/null
diff --git a/server/bin/setserveraddr b/server/bin/setserveraddr
index a979595f..eb52d64d 100755
--- a/server/bin/setserveraddr
+++ b/server/bin/setserveraddr
@@ -22,7 +22,7 @@
PROG="$(basename "$0")"
OPENGNSYS=/opt/opengnsys
PXEDIR=$OPENGNSYS/tftpboot/menu.lst
-CONFIGFILE=$OPENGNSYS/etc/opengnsys.json
+DEFAULTFILE=/etc/default/opengnsys
# Checking parameters.
if [ $# -ne 1 ]; then
@@ -56,7 +56,8 @@ done
if [ -n "$SERVERIP" ]; then
# Temporary files.
tmpfile=$(mktemp /tmp/og.XXXXX)
- trap "rm -f $tmpfile" 1 2 3 6 9 15
+ MYCNF=$(mktemp /tmp/.my.cnf.XXXXX)
+ trap "rm -f $tmpfile $MYCNF" 1 2 3 6 9 15
# Checking whether the DHCP settings need to be changed.
CHANGE=0
@@ -84,12 +85,73 @@ if [ -n "$SERVERIP" ]; then
echo "DHCP configuration has not changed."
fi
- OLDSERVERIP=$(jq -r .server.ip $CONFIGFILE)
- if [ "$SERVERIP" != "$OLDSERVERIP" ]; then
- # Updating configuration file.
- jq ".server.ip=\"$SERVERIP\"" $CONFIGFILE | sponge $CONFIGFILE
- # Updating all PXE files.
- find $PXEDIR -name "01-*" -exec sed -i -e "s/$OLDSERVERIP/$SERVERIP/g" {} \;
+ # Saving old IP address.
+ source $OPENGNSYS/etc/ogAdmRepo.cfg
+ OLDSERVERIP=$IPlocal
+
+ # Checking if configuration files need to be modified.
+ CHANGE=0
+ for f in $OPENGNSYS/{etc/{ogAdmServer,ogAdmRepo,ogAdmAgent}.cfg,www/controlacceso.php,client/etc/ogAdmClient.cfg}; do
+ # Error if configuration file cannot be found.
+ if [ ! -f $f ]; then
+ echo "$PROG: File $file does not exist." >&2
+ exit 2
+ fi
+ # Updating configuration variables (if URLs does not contain "localhost").
+ sed -e "s,ServidorAdm=.*,ServidorAdm=$SERVERIP," \
+ -e "s,IPlocal=.*,IPlocal=$SERVERIP," \
+ -e "s,UrlMenu=https?://\([^/]*\)/\(.*\),UrlMenu=https://$SERVERIP/\2," \
+ -e '/localhost/!s,https\?://[^/]*/\(.*\),https://'$SERVERIP'/\1,' $f >$tmpfile
+ file="${f/./-$SERVERDEV.}"
+ # Copying updated file, if needed.
+ if [ ! $f -ef $file ] || ! diff -q $tmpfile $file &>/dev/null; then
+ cp $tmpfile $file
+ ln -f $file $f
+ CHANGE=1
+ fi
+ done
+
+ # Processing when something has changed.
+ if [ $CHANGE == 1 ]; then
+ # Restart OpenGnsys services.
+ /etc/init.d/opengnsys restart
+ # If Repository is active, generating a new API token.
+ source $DEFAULTFILE
+ if [ "$RUN_OGADMREPO" == "yes" ]; then
+ REPOKEY=$(php -r 'echo md5(uniqid(rand(), true));')
+ sed -i -e "s/ApiToken=.*/ApiToken=$REPOKEY/" $OPENGNSYS/etc/ogAdmRepo.cfg
+ fi
+ # If OpenGnsys Server is active, updating the database.
+ if [ "$RUN_OGADMSERVER" == "yes" ]; then
+ source $OPENGNSYS/etc/ogAdmServer.cfg
+ # Creating credentials file.
+ cat << EOT > $MYCNF
+[client]
+user=$USUARIO
+password=$PASSWORD
+EOT
+ # Updating OpenGnsys Server IP address.
+ mysql --defaults-extra-file=$MYCNF -D "$CATALOG" -e \
+ "UPDATE entornos
+ SET ipserveradm='$SERVERIP'
+ WHERE identorno=1"
+ # If OpenGnsys Repository is active, updating IP address and API token.
+ if [ "$RUN_OGADMREPO" == "yes" ]; then
+ mysql --defaults-extra-file=$MYCNF -D "$CATALOG" -e \
+ "UPDATE repositorios
+ SET ip='$SERVERIP', apikey='$REPOKEY'
+ WHERE ip='$OLDSERVERIP'"
+ unset REPOKEY
+ fi
+ # Updating all menu URLs.
+ mysql --defaults-extra-file=$MYCNF -D "$CATALOG" -e \
+ "UPDATE menus
+ SET htmlmenupub = REPLACE(htmlmenupub, '$OLDSERVERIP', '$SERVERIP'),
+ htmlmenupri = REPLACE(htmlmenupri, '$OLDSERVERIP', '$SERVERIP');"
+ # Updating all PXE files.
+ find $PXEDIR -name "01-*" -exec sed -i -e "s/$OLDSERVERIP/$SERVERIP/g" {} \;
+ fi
+
# Showing manual task to do after execution.
cat << EOT
Default server interface set to: $SERVERDEV ($SERVERIP)
@@ -99,6 +161,7 @@ Manual tasks:
- Check PXE files.
- Log-in as Web Console user:
- Check menu URLs.
+${REPOKEY:+" - Update repository API token"}
EOT
else
# Showing message if nothing changes.
@@ -110,6 +173,6 @@ else
exit 1
fi
-# Removing temporary file.
-rm -f $tmpfile
+# Removing temporary files.
+rm -f $tmpfile $MYCNF
diff --git a/server/bin/setserveraddr3 b/server/bin/setserveraddr3
new file mode 100755
index 00000000..a979595f
--- /dev/null
+++ b/server/bin/setserveraddr3
@@ -0,0 +1,115 @@
+#!/bin/bash
+
+#/**
+# setserveraddr {str_ipaddress | str_netiface}
+#@file setserveraddr
+#@brief Command the modifies configuration files to assign the default network interface.
+#@param str_ipaddress IP address assigned to a network interface
+#@param str_netiface network interface name defined by the operating system.
+#@version Initial version.
+#@author Ramón M. Gómez - ETSII Univ. Sevilla
+#@date 2011-01-25
+#@version 1.0.5 - Regenerate configuration files.
+#@author Ramón M. Gómez - ETSII Univ. Sevilla
+#@date 2014-06-06
+#@version 1.1.1 - Updating menu URLs, PXE files, and repository API key.
+#@author Ramón M. Gómez - ETSII Univ. Sevilla
+#@date 2018-11-15
+#*/ ##
+
+
+# Variables.
+PROG="$(basename "$0")"
+OPENGNSYS=/opt/opengnsys
+PXEDIR=$OPENGNSYS/tftpboot/menu.lst
+CONFIGFILE=$OPENGNSYS/etc/opengnsys.json
+
+# Checking parameters.
+if [ $# -ne 1 ]; then
+ echo "$PROG: Incorrect operand. Format: $PROG ipaddress|netiface" >&2
+ exit 1
+fi
+if [ "$USER" != "root" ]; then
+ echo "$PROG: Need to be root." >&2
+ exit 1
+fi
+
+# Showing warning to inform that initiated clients may hang.
+read -rp "WARNING: initiated clients can hang. Continue? (y/n): " ANSWER
+if [ "${ANSWER,,}" != "y" ]; then
+ echo "Operation canceled."
+ exit 0
+fi
+
+# Detecting network interfaces.
+DEVICES=$(ip -o link show up | awk -F: '$2!~/lo/ {print $2}')
+for DEV in $DEVICES; do
+ # If the network interface is found, get its IP address.
+ IP=$(ip -o addr show dev "$DEV" | awk '$3~/inet$/ {sub (/\/.*/, ""); print ($4)}')
+ if [ "$DEV" == "$1" ] || [ "$IP" == "$1" ]; then
+ SERVERIP="$IP"
+ SERVERDEV="$DEV"
+ fi
+done
+
+# Checking if IP address has been detected.
+if [ -n "$SERVERIP" ]; then
+ # Temporary files.
+ tmpfile=$(mktemp /tmp/og.XXXXX)
+ trap "rm -f $tmpfile" 1 2 3 6 9 15
+
+ # Checking whether the DHCP settings need to be changed.
+ CHANGE=0
+ for f in /etc/{dhcp,hcp3}/dhcpd.conf; do
+ if [ -f $f ]; then
+ # Changing DHCP "next-server" parameter.
+ file="${f/./-$SERVERDEV.}"
+ sed -e "s/next-server.*/next-server $SERVERIP;/" \
+ -e "s/option routers ;/option routers ${SERVERIP%.*}.1;/" $file >$tmpfile
+ # Copying and linking file if there are changes.
+ if [ ! $f -ef $file ] || ! diff -q $tmpfile $file &>/dev/null; then
+ mv $tmpfile $file
+ chmod 644 $file
+ ln -f $file $f
+ CHANGE=1
+ fi
+ fi
+ done
+ # Restarting DHCP service if its configuration has changed.
+ if [ $CHANGE == 1 ]; then
+ for f in /etc/init.d/{isc-dhcp-server,dhcp3-server,dhcpd}; do
+ [ -x $f ] && $f restart
+ done
+ else
+ echo "DHCP configuration has not changed."
+ fi
+
+ OLDSERVERIP=$(jq -r .server.ip $CONFIGFILE)
+ if [ "$SERVERIP" != "$OLDSERVERIP" ]; then
+ # Updating configuration file.
+ jq ".server.ip=\"$SERVERIP\"" $CONFIGFILE | sponge $CONFIGFILE
+ # Updating all PXE files.
+ find $PXEDIR -name "01-*" -exec sed -i -e "s/$OLDSERVERIP/$SERVERIP/g" {} \;
+ # Showing manual task to do after execution.
+ cat << EOT
+Default server interface set to: $SERVERDEV ($SERVERIP)
+
+Manual tasks:
+- Check DHCP configuration file and restart service, if needed.
+- Check PXE files.
+- Log-in as Web Console user:
+ - Check menu URLs.
+EOT
+ else
+ # Showing message if nothing changes.
+ echo "Default interface has not changed: $1"
+ fi
+else
+ # Error if network interface is not found.
+ echo "$PROG: Network device not found. Format: $PROG ipaddress|netiface" >&2
+ exit 1
+fi
+
+# Removing temporary file.
+rm -f $tmpfile
+