From 2117425a8f5dd6762b7f4a7ca4569dbbacd06c03 Mon Sep 17 00:00:00 2001
From: "Eduardo L. Buratti" <elb09@c3sl.ufpr.br>
Date: Tue, 23 Jul 2013 10:17:46 -0300
Subject: [PATCH] Copy bootstrap files from buildpackage to build

---
 build/bootstraps/bootstrap-install.sh | 277 ++++++++++++++++++++++++++
 build/bootstraps/bootstrap-update.sh  | 157 +++++++++++++++
 2 files changed, 434 insertions(+)
 create mode 100755 build/bootstraps/bootstrap-install.sh
 create mode 100755 build/bootstraps/bootstrap-update.sh

diff --git a/build/bootstraps/bootstrap-install.sh b/build/bootstraps/bootstrap-install.sh
new file mode 100755
index 0000000..c9d178f
--- /dev/null
+++ b/build/bootstraps/bootstrap-install.sh
@@ -0,0 +1,277 @@
+#!/bin/bash
+# Copyright (C) 2009-2012 Centro de Computacao Cientifica e Software Livre
+# Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+#
+# This file is part of buildpackage
+#
+# buildpackage is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
+# USA.
+
+# This is the installation bootstrap
+
+# ------------------------------------------------------------------------------
+# This function checks the integrity of the tar package
+verify_md5(){
+    printf "Verificando MD5... " >&3
+    if [[ ${MD5_CHECK} == $(md5sum ${FILE} | awk '{print $1}') ]] ; then
+        printf "OK!\n" >&3
+    else
+        printf "ERRO: Este pacote está corrompido. %b" \
+               "Por favor, faça um novo download.\n" >&3
+        rm -rf "${FILE}" &> /dev/null
+        exit 4
+    fi
+}
+
+# ------------------------------------------------------------------------------
+# This function collects the agent log, data and runs some tests, in case some
+# error ocurred during the installation
+collect_information(){
+    printf "\nAlgumas informações referentes ao agente PROINFODATA %b%b%b%b" \
+           "recém instalado serão coletadas. O resultado da coleta " \
+           "será armazenado no arquivo temporário \"${LOGFILE}\". Favor " \
+           "enviar esse arquivo para \"proinfodata@c3sl.ufpr.br\". Assim " \
+           "a equipe ficará ciente do problema para resolvê-lo.\n\n" >&3
+
+    printf "Iniciando coleta das informações (isso pode demorar alguns %b" \
+           "minutos)... " >&3
+
+    printf "    Configuration files\n%b" \
+           "    ===================\n\n"
+    printf "version\n"
+    cat ${AGENT_DIR}/client/conf/version
+    printf "proxy\n"
+    cat ${AGENT_DIR}/client/conf/proxy
+    printf "inep\n"
+    cat ${AGENT_DIR}/client/conf/inep
+    printf "\n\n----------------------------------\n\n"
+
+    printf "    OS information\n%b" \
+           "    ==============\n\n"
+    printf "Distro\n"
+    DISTRO=$(cut -sd ' ' -f1 /etc/issue | head -n 1)
+    if test -f "/etc/le_version"; then
+      printf "Linux Educacional $(cat /etc/le_version)\n"
+    elif test "${DISTRO}" = "Ubuntu" -a -f "/usr/lib/edu/fbedu/tutorial.htm"; then
+      printf "Linux Educacional\n"
+    elif test "${DISTRO}" = "Mandriva"; then
+      head -n 1 /etc/issue
+    elif test "${DISTRO}" = "Welcome"; then
+      cut -sd "\\" -f1 /etc/issue | cut -d ' ' -f3-
+    else
+      cut -sd "\\" -f1 /etc/issue
+    fi
+    printf "Kernel\n"
+    cut -d " " -f3 /proc/version
+    printf "\n\n----------------------------------\n\n"
+
+    printf "    Commands\n%b" \
+           "    ========\n\n"
+    printf "seed_mec user crontab\n"
+    crontab -u seed_mec -l
+    printf "ifconfig\n"
+    /sbin/ifconfig
+    printf "route\n"
+    /sbin/route
+    printf "Routes test\n"
+    for interface in $(/sbin/route | grep default | awk '{print $NF}'); do
+        printf "Tested interface: ${interface}\n"
+        # Send ICMP ECHO_REQUEST to root server I or J
+        ping -c 1 -I ${interface} 192.36.148.17
+        ping -c 1 -I ${interface} 192.58.128.30
+    done
+    printf "\n\n----------------------------------\n\n"
+
+    printf "    seed_mec user files\n%b" \
+           "    ===================\n\n"
+    ls -lR "${SEED_MEC_HOME}"
+    printf "\n\n----------------------------------\n\n"
+
+    printf "    Inventory XML\n%b" \
+           "    =============\n\n"
+    cat ${AGENT_DIR}/data/collect-data.xml
+    printf "\n\n----------------------------------\n\n"
+
+    printf "    run.sh\n%b" \
+           "    ========\n\n"
+    cat ${AGENT_DIR}/client/run.sh
+    printf "\n\n----------------------------------\n\n"
+
+    printf "    agent.sh\n%b" \
+           "    ========\n\n"
+    cat ${AGENT_DIR}/agent.sh
+    printf "\n\n----------------------------------\n\n"
+
+    printf "    Collect agent log\n%b" \
+           "    =================\n\n"
+    cat ${AGENT_DIR}/log/collect.log
+    printf "\n\n----------------------------------\n\n"
+
+    printf "    Web service client log\n%b" \
+           "    ======================\n\n"
+    cat ${AGENT_DIR}/client/run.log
+    printf "\n\n----------------------------------\n\n"
+
+    printf "    TincUCA client log\n%b" \
+           "    ==================\n\n"
+    cat ${AGENT_DIR}/log/tincucaclient-install.log
+    printf "\n\n----------------------------------\n\n"
+
+    printf "feito!\n\nFavor enviar o arquivo temporário \"${LOGFILE}\"%b%b%b" \
+           " para \"proinfodata@c3sl.ufpr.br\".\n\n" \
+           "Em caso de dúvidas, acesse o portal do PROINFODATA:\n" \
+           "proinfodata.c3sl.ufpr.br\n" >&3
+}
+
+# ------------------------------------------------------------------------------
+printf "Iniciando instalação do agente PROINFODATA. Tenha certeza de %b%b%b" \
+       "estar conectado à Internet e executando este arquivo como super-" \
+       "usuário (root). Além disso, para o agente funcionar é necessário " \
+       "ter instalado no sistema os pacotes \"cron\" e \"sudo\".\n"
+
+# These variables will be replaced when generating the installation package
+MD5_CHECK=
+BOOTSTRAP_LINES=
+
+# Set variables
+FILE="SEED2.tgz"
+PROJECTOR=$(grep "Projetor ProInfo" /etc/issue 2> /dev/null)
+UCA_SERVER=$(grep "Metasys School Server" /etc/issue 2> /dev/null)
+UCA_CLASSMATE=$(grep "Metasys ClassmatePC" /etc/issue 2> /dev/null)
+if test -f "/usr/sbin/projetor" -o -n "${PROJECTOR}"; then
+    SEED_MEC_HOME="/mnt/conf/seed_mec"
+else
+    SEED_MEC_HOME="/opt/seed_mec"
+fi
+AGENT_DIR="${SEED_MEC_HOME}/SEED2"
+LASTEXEC="${AGENT_DIR}/tmp/lastExec.tmp"
+LOGFILE=/tmp/collected-information.log
+# Save stdout to file descriptor 3 and redirect all output to $LOGFILE
+exec 3>&1 &> ${LOGFILE}
+
+# Check if lastExec.tmp exist then save its content to prevent that
+# agent send a inventory more than once per day
+if test -f ${LASTEXEC}; then 
+	LASTEXECBACKUP=$(cat ${LASTEXEC})
+fi
+ 
+# Remove any previous installation of the agent
+rm -rf "${AGENT_DIR}"
+/usr/sbin/userdel -r seed_mec
+/usr/sbin/groupdel seed_mec
+
+# Create seed_mec group and exit on error (except by the error of previous
+# existence of seed_mec group)
+if ! /usr/sbin/groupadd -f seed_mec; then
+    printf "ERRO: Falha ao criar o grupo seed_mec.\n" >&3
+    exit 1
+fi
+
+# Create the directory path to make sure useradd(1) will be able to create the
+# home for seed_mec user
+mkdir -p "$(dirname ${SEED_MEC_HOME})"
+
+# This is a temporary skel directory to avoid installing in the default skel
+TMPSKEL=$(mktemp -d)
+
+# Create seed_mec user with seed_mec as group, BASH as default shell,
+# $SEED_MEC_HOME as home and $TMPSKEL as temporary skel
+/usr/sbin/useradd -r -m -g seed_mec -s /bin/bash -d "${SEED_MEC_HOME}" \
+        -k "${TMPSKEL}" seed_mec
+RETVAL=$?
+
+# If an error occurred (return isn't 0), besides the previous existence of
+# seed_mec user (return 9, which means the agent will be reinstalled), print an
+# error message and exit
+if test ${RETVAL} -ne 0 -a ${RETVAL} -ne 9; then
+    printf "ERRO: Falha ao criar o usuário seed_mec.\n" >&3
+    exit 2
+fi
+
+# Remove the temporary skel, as it isn't needed anymore
+rmdir "${TMPSKEL}"
+
+# ------------------------------------------------------------------------------
+# Ensure seed_mec's home exists
+mkdir -p "${SEED_MEC_HOME}"
+
+# Remove old crontab of seed_mec, in case there's one, avoinding a specific
+# error of wrong owner (lack of permissions)
+crontab -u seed_mec -r
+
+# Check if this is not an UCA Classmate, UCA Server nor PROINFO Projector, and
+# if the line that gives root permission doesn't exist before adding it
+if ! test -n "${PROJECTOR}" -o -f "/usr/sbin/projetor" -o \
+          -f "/etc/cmpc-release" -o -n "${UCA_SERVER}" -o \
+          -n "${UCA_CLASSMATE}"; then
+    # Remove any possible line containing a rule for seed_mec user before adding
+    # root permissions in the sudoers file
+    TMPFILE=$(mktemp)
+    sed '/^seed_mec[\t ]*ALL=(ALL/d' /etc/sudoers > "${TMPFILE}"
+    mv "${TMPFILE}" /etc/sudoers
+    chmod 440 /etc/sudoers
+    # Add root permissions to seed_mec user, without the need of password
+    if ! $(echo -e "seed_mec\tALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers)
+    then
+        printf "ERRO: Falha ao adicionar permissões de super-usuário %b" \
+           "ao usuário seed_mec.\n" >&3
+        exit 3
+    fi
+fi
+
+# ------------------------------------------------------------------------------
+# Uncompress tar package and check its integrity
+tail -n +${BOOTSTRAP_LINES} $0 > "${SEED_MEC_HOME}/${FILE}"
+cd "${SEED_MEC_HOME}"
+verify_md5
+
+# Remove old agent and extract the new one
+rm -rf "${AGENT_DIR}" &> /dev/null
+tar xzf "${FILE}" &> /dev/null
+rm -rf "${FILE}" &> /dev/null
+
+# Change files' owner
+if ! chown -R seed_mec:seed_mec "${SEED_MEC_HOME}"; then
+    rm -rf "${SEED_MEC_HOME}" &> /dev/null
+    printf "ERRO: Falha ao mudar dono dos arquivos.\n" >&3
+    exit 5
+fi
+
+# ------------------------------------------------------------------------------
+# Export a variable to inform the agent that this is its first execution
+export FIRST_EXECUTION=1
+
+# Restore lastExec.tmp
+if ! test -z ${LASTEXECBACKUP};then  
+	echo ${LASTEXECBACKUP} > ${LASTEXEC}
+fi
+
+# Run the agent and check if its execution went alright, exiting in case of
+# error
+if ! su -c "bash ${AGENT_DIR}/update.sh" seed_mec ||
+    ! su -c "bash ${AGENT_DIR}/inventory.sh" seed_mec; then
+    printf "ERRO: Falha na execução do novo agente.\n" >&3
+    collect_information
+    exit 6
+fi
+
+# Restore stdout and close fd 3
+exec >&3 3>&-
+
+printf "\nO agente PROINFODATA foi instalado com sucesso. %b%b" \
+       "Em caso de dúvidas, acesse o portal do PROINFODATA:\n" \
+       "proinfodata.c3sl.ufpr.br\n"
+
+exit 0
diff --git a/build/bootstraps/bootstrap-update.sh b/build/bootstraps/bootstrap-update.sh
new file mode 100755
index 0000000..3cd2175
--- /dev/null
+++ b/build/bootstraps/bootstrap-update.sh
@@ -0,0 +1,157 @@
+#!/bin/bash
+# Copyright (C) 2009-2012 Centro de Computacao Cientifica e Software Livre
+# Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
+#
+# This file is part of buildpackage
+#
+# buildpackage is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
+# USA.
+
+# This is the update bootstrap
+
+# ------------------------------------------------------------------------------
+# This function verifies if the package MD5 is correct
+verify_md5(){
+    printf "[SEED2-update] Checking MD5... "
+    if [[ ${MD5_CHECK} == $(md5sum "${SEED_MEC_HOME}/update/tmp/${FILE}" | \
+                            awk '{print $1}') ]]; then
+        printf "OK!\n"
+    else
+        printf "ERROR: This package is currupted.\n"
+        rm -rf ${FILE} &> /dev/null
+        exit 1
+    fi
+}
+
+# ------------------------------------------------------------------------------
+# Re-create the inep and proxy's MD5
+restore_inep_proxy_md5sum(){
+    for FILE in inep proxy; do
+        md5sum "${SEED_MEC_HOME}/SEED2/client/conf/${FILE}" |cut -d' ' -f1 > \
+               "${SEED_MEC_HOME}/${UPDATE_DIR}/.md5sum/client/conf/${FILE}"
+
+        # The backup md5 is the same
+        cp -a "${SEED_MEC_HOME}/${UPDATE_DIR}/.md5sum/client/conf/${FILE}" \
+               "${SEED_MEC_HOME}/${UPDATE_DIR}/.md5sum/.backup/client/conf/"
+    done
+}
+
+# ------------------------------------------------------------------------------
+# Re-create the inep and proxy files' backup and copy the MD5 files
+restore_inep_proxy_backup(){
+    for FILE in inep proxy; do
+        # The backup itself
+        cp -a "${SEED_MEC_HOME}/SEED2/client/conf/${FILE}" \
+              "${SEED_MEC_HOME}/${UPDATE_DIR}/.backup/client/conf/"
+    done
+}
+
+# ------------------------------------------------------------------------------
+# These variables will be replaced while generating the package
+FILE=
+MD5_CHECK=
+BOOTSTRAP_LINES=
+
+if test -n "${HOME}"; then
+    SEED_MEC_HOME=${HOME}
+else
+    SEED_MEC_HOME=/opt/seed_mec
+fi
+UPDATE_DIR="update/tmp/SEED2-run"
+
+# ------------------------------------------------------------------------------
+# Create auxiliar directories
+mkdir -p "${SEED_MEC_HOME}/update/tmp"
+mkdir -p "${SEED_MEC_HOME}/update/old"
+
+# Extract the tar package
+tail -n +${BOOTSTRAP_LINES} "$0" > "${SEED_MEC_HOME}/update/tmp/${FILE}"
+verify_md5
+cd "${SEED_MEC_HOME}/update/tmp"
+tar xzf "${FILE}" &> /dev/null
+cd - &> /dev/null
+
+# ------------------------------------------------------------------------------
+# Make sure the directories exist in the update tree to backup the inep and
+# proxy files, along with their counterparts (backup and MD5)
+mkdir -p "${SEED_MEC_HOME}/update/tmp/SEED2-run/client/conf"
+mkdir -p "${SEED_MEC_HOME}/update/tmp/SEED2-run/.md5sum/client/conf"
+mkdir -p "${SEED_MEC_HOME}/update/tmp/SEED2-run/.backup/client/conf"
+mkdir -p "${SEED_MEC_HOME}/update/tmp/SEED2-run/.md5sum/.backup/client/conf"
+
+# Check if the inep and proxy files exist
+ERROR=0
+INEP_PROXY="${SEED_MEC_HOME}/SEED2/client/conf/inep
+            ${SEED_MEC_HOME}/SEED2/client/conf/proxy"
+for FILE in ${INEP_PROXY}; do
+    test -f "${FILE}" || ERROR=1
+done
+
+# Copy the inep and proxy files. Also, copy their backups and MD5 counterparts,
+# if they exist. Otherwise, create them
+if test "${ERROR}" -eq 0; then
+
+    # Copy inep and proxy to the new tree
+    cp -a "${SEED_MEC_HOME}/SEED2/client/conf/"{inep,proxy} \
+          "${SEED_MEC_HOME}/update/tmp/SEED2-run/client/conf/"
+
+    # Copy or create the md5 files from inep and proxy
+    (test -d "${SEED_MEC_HOME}/SEED2/.md5sum" &&
+        cp -a "${SEED_MEC_HOME}/SEED2/.md5sum/client/conf/"{inep,proxy} \
+              "${SEED_MEC_HOME}/update/tmp/SEED2-run/.md5sum/client/conf/" &&
+        cp -a "${SEED_MEC_HOME}/SEED2/.md5sum/.backup/client/conf/"{inep,proxy} \
+              "${SEED_MEC_HOME}/update/tmp/SEED2-run/.md5sum/.backup/client/conf/") ||
+    restore_inep_proxy_md5sum
+
+    # Copy or create the backup files from inep and proxy
+    (test -d "${SEED_MEC_HOME}/SEED2/.backup" &&
+        cp -a "${SEED_MEC_HOME}/SEED2/.backup/client/conf/"{inep,proxy} \
+              "${SEED_MEC_HOME}/update/tmp/SEED2-run/.backup/client/conf/") ||
+    restore_inep_proxy_backup
+
+fi
+
+# ------------------------------------------------------------------------------
+# TODO: do some security backup???
+#cp -ra "${SEED_MEC_HOME}/SEED2/" "${SEED_MEC_HOME}/old/"
+
+# If something interrupts the script here, the tree will not be entirely
+# correct, so a file is created to mark that something happened. During the next
+# next execution the package will try to recover itself
+##### CRITICAL #####
+touch "${SEED_MEC_HOME}/SEED2/updating"
+
+# md5sum and backup folders
+rm -rf "${SEED_MEC_HOME}/SEED2/.md5sum" \
+       "${SEED_MEC_HOME}/SEED2/.backup" &> /dev/null
+mv -f "${SEED_MEC_HOME}/update/tmp/SEED2-run/"{.md5*,.back*}* \
+      "${SEED_MEC_HOME}/SEED2/"
+
+# Copy the files themself
+rm -rf "${SEED_MEC_HOME}/SEED2/"{bin,lib,net,client,extra,network-scripts,scripts} &> /dev/null
+mv -f "${SEED_MEC_HOME}/update/tmp/SEED2-run/"* \
+      "${SEED_MEC_HOME}/SEED2/"
+
+rm -f "${SEED_MEC_HOME}/SEED2/updating" &> /dev/null
+### END CRITICAL ###
+
+# ------------------------------------------------------------------------------
+# Remove auxiliar directories
+rm -rf "${SEED_MEC_HOME}/update" &> /dev/null
+
+# Call the agent
+"${SEED_MEC_HOME}/SEED2/update.sh"
+
+exit 0
-- 
GitLab