#!/usr/bin/bash

set -eE

function anomaly_handler() {
  echo ""
  echo "ERROR: An error happened during the step: ${STEP} (l $1)"
  echo "ERROR: The migration will now stop"
  echo "ERROR: Please try to run /opt/rudder/bin/rudder-upgrade again"
}

trap 'anomaly_handler ${LINENO}' ERR INT TERM

#####################################################################################
# Copyright 2012 Normation SAS
#####################################################################################
#
# This program 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, Version 3.
#
# 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, see <http://www.gnu.org/licenses/>.
#
################################################################################

#####################################################################################
# Upgrade script for Rudder
#####################################################################################
# Currently this script doesn't discriminate on versions, it just always runs
# all the tests and tries to upgrade what it can. It may in the future.
#
# This is mostly OK, because adding unused properties to the
# /opt/rudder/etc/rudder-web.properties configuration file is harmless.
#
# Upgrade checks currently implemented:
# - All versions : Check if access credentials in rudder-web.properties match the ones from rudder-passwords.conf
# - All versions : upgrade system Techniques automatically and reload the Technique library
# - All versions : Check that Rudder database is able to handle backslash
# - All versions : Check for the PostgreSQL version
# - All versions : Create ncf technique update flag and restart at the end of the script
####################################################################################

# Some paths
RUDDER_OPT="/opt/rudder"
RUDDER_VAR="/var/rudder"
CONFIGURATION_REPOSITORY="${RUDDER_VAR}/configuration-repository"
RUDDER_SHARE="${RUDDER_OPT}/share"
RUDDER_NCF_SOURCE_DIRECTORY="/usr/share/ncf"
RUDDER_UPGRADE_TOOLS="${RUDDER_SHARE}/upgrade-tools"

# If true, display a message at the end, asking to re-run the script
INCOMPLETE_MIGRATION=false

# Ensure our PATH includes Rudder's binaries
export PATH=${PATH}:${RUDDER_OPT}/bin

# Set to defined value if not defined by environment
: ${RUDDER_NO_TECHNIQUE_AUTOCOMMIT:=0}

# Get how many access credentials we got for LDAP and SQL in /opt/rudder/etc/rudder-web.properties
# (should have 2 for each, user and password)
LDAP_CREDENTIALS=$(grep -c -E "^ldap.auth(dn|pw)[ \t]*=" /opt/rudder/etc/rudder-web.properties || true)
SQL_CREDENTIALS=$(grep -c -E "^rudder.jdbc.(username|password)[ \t]*=" /opt/rudder/etc/rudder-web.properties || true)

TOTAL_CREDENTIALS=$((LDAP_CREDENTIALS+SQL_CREDENTIALS))

LDAP_SERVER='localhost'
LDAP_PORT='389'
if [ -f /opt/rudder/etc/rudder-web.properties -a ${TOTAL_CREDENTIALS} -eq 4 ]; then
  # Get the database access credentials from the rudder-web.properties file
  LDAP_USER="$(grep -E '^ldap.authdn[ \t]*=' ${RUDDER_OPT}/etc/rudder-web.properties | cut -d "=" -f 2-)"
  LDAP_PASSWORD="$(grep -E '^ldap.authpw[ \t]*=' ${RUDDER_OPT}/etc/rudder-web.properties | cut -d "=" -f 2-)"

  SQL_USER="$(grep -E '^rudder.jdbc.username[ \t]*=' ${RUDDER_OPT}/etc/rudder-web.properties | cut -d "=" -f 2-)"
  SQL_PASSWORD="$(grep -E '^rudder.jdbc.password[ \t]*=' ${RUDDER_OPT}/etc/rudder-web.properties | cut -d "=" -f 2-)"
  SQL_SERVER="$(grep -E '^rudder.jdbc.url[ \t]*=' ${RUDDER_OPT}/etc/rudder-web.properties | cut -d '=' -f 2- | sed 's%^.*://\(.*\):\(.*\)/.*$%\1%')"
  SQL_PORT="$(grep -E '^rudder.jdbc.url[ \t]*=' ${RUDDER_OPT}/etc/rudder-web.properties | cut -d '=' -f 2- | sed 's%^.*://\(.*\):\(.*\)/.*$%\2%')"
  SQL_DATABASE="$(grep -E '^rudder.jdbc.url[ \t]*=' ${RUDDER_OPT}/etc/rudder-web.properties | cut -d '=' -f 2- | sed 's%^.*://.*:.*/\(.*\)$%\1%')"

  export PGPASSWORD="${SQL_PASSWORD}"
else
  # No database access credentials in rudder-web.properties... Try anyway using "guessed" values.
  echo "WARNING: Database access credentials are missing in /opt/rudder/etc/rudder-web.properties, trying to guess adequate values."
  LDAP_USER=$(grep "^rootdn" /opt/rudder/etc/openldap/slapd.conf | sed "s/\w*\s*['\"]\?\([^\"']*\)['\"]\?$/\1/")
  LDAP_PASSWORD=$(grep "^rootpw" /opt/rudder/etc/openldap/slapd.conf | sed "s/\w*\s*['\"]\?\([^\"']*\)['\"]\?$/\1/")

  SQL_USER="rudder"
  SQL_PASSWORD="Normation"
  SQL_SERVER="localhost"
  SQL_PORT="5432"
  SQL_DATABASE="rudder"

  # We rely on .pgpass instead
  unset PGPASSWORD
fi

# Override any server values with those from ${RUDDER_ROLES_FILE}, unless this is a monolithic
# Rudder server installation (to keep using localhost)
RUDDER_ROLES_FILE="${RUDDER_VAR}/cfengine-community/inputs/rudder-server-roles.conf"
if [ -f ${RUDDER_ROLES_FILE} ]; then
  ROLE_HOSTNAME=$(grep "^rudder-db:" ${RUDDER_ROLES_FILE} | cut -d: -f2 | cut -d, -f1 | tr -d " ")
  if [ ! -z ${ROLE_HOSTNAME} ]; then
    SQL_SERVER=${ROLE_HOSTNAME}
  fi
fi

# Commands
LDAP_PARAMETERS="-H ldap://${LDAP_SERVER}:${LDAP_PORT}/ -D ${LDAP_USER} -w ${LDAP_PASSWORD} -x"

LDAPSEARCH="ldapsearch ${LDAP_PARAMETERS} -LLL"
LDAPMODIFY="ldapmodify ${LDAP_PARAMETERS}"
LDAPADD="ldapadd ${LDAP_PARAMETERS}"

PSQL="psql -q -h ${SQL_SERVER} -p ${SQL_PORT} -U ${SQL_USER}"

################################################################################
# Helper functions
################################################################################

# Helper function
# Function to check if a property exists in a configuration file and add it if not
# Parameters:
# - $1 = property name
# - $2 = value to add
check_and_add_config_property() {
  PROPERTY_NAME=$1
  PROPERTY_VALUE=$2
  ATTRIBUTESET=$(grep -c "^${PROPERTY_NAME}[ \t]*=" /opt/rudder/etc/rudder-web.properties || true)
  if [ ${ATTRIBUTESET} -eq 0 ]; then
echo "${PROPERTY_VALUE}" >> /opt/rudder/etc/rudder-web.properties
    echo "INFO: New configuration property ${PROPERTY_NAME} added to /opt/rudder/etc/rudder-web.properties"
  fi
}

# Helper function
# Function to launch a service status check and retry to poll it in case of a failure
# Parameters:
# - $1 = command to execute
# - $2 = service name
retry_wrapper() {
  tries=0; MAXTRIES=10;
  while [ ${tries} -lt ${MAXTRIES} ]; do
    eval ${1} && RET_SSH=0 || RET_SSH=$?
    # Did we succeed?
    if [ ${RET_SSH} -eq 0 ]; then return 0; fi
    # OK, we failed
    tries=$((${tries}+1))
    if [ ${tries} -ge ${MAXTRIES} ]; then
      echo " FAILED" # we are on a line that says "Checking ...", so finish it before printing anything else
      echo "${2} service verification failed after ${MAXTRIES} tries."
      return 1
    else
      echo -n "."
      /bin/sleep 2
    fi
  done
}

# Helper function
# Function to update rudder's configuration repository from a system directory
# Parameters:
# - $1 = origin directory
# - $2 = destination directory (in configuration repository)
update_rudder_repository_from_system_directory() {
  # Prime work variables first
  SRCTECHDIR="${1}"
  TRGTECHDIR="${CONFIGURATION_REPOSITORY}/${2}"

  mkdir -p "${TRGTECHDIR}"

  if ! diff -Naur ${SRCTECHDIR} ${TRGTECHDIR} >/dev/null 2>&1; then
    rsync --delete --ignore-times -rptgoq ${SRCTECHDIR} ${TRGTECHDIR}
    if [ x"${RUDDER_NO_TECHNIQUE_AUTOCOMMIT}" != x"1" ]; then
      cd ${CONFIGURATION_REPOSITORY}/ && git add -A ${2} && git commit -m "Upgrade system Techniques from ${SRCTECHDIR} - automatically done by rudder-upgrade script" >/dev/null 2>&1
      # Schedule a Technique library reload later because of the update
      echo "INFO: A Technique library reload is needed and has been scheduled."
      touch /opt/rudder/etc/force_technique_reload
    else
      echo "WARN: Autocommit of system techniques is disabled."
      echo "Please review and commit changes, then reload technique library on your own!"
    fi
  fi
}

# Helper function
# Function to remove deprecated system technique from the system directory
# It also removes it from /opt/rudder/share/techniques/system directory (see https://issues.rudder.io/issues/20356 )
# Parameters:
# - $1 = technique name
remove_system_technique_from_system_directory() {
  TECHNAME="${1}"
  LOCALTECHDIR="techniques/system/${TECHNAME}"
  TECHDIR="${CONFIGURATION_REPOSITORY}/${LOCALTECHDIR}"
  INITTECHDIR="/opt/rudder/share/${LOCALTECHDIR}"

  if [ -d ${TECHDIR} ]; then
    rm -rf ${TECHDIR}
    cd ${CONFIGURATION_REPOSITORY}/ && git rm -rf ${LOCALTECHDIR} >/dev/null 2>&1
    git commit -m "Remove deprecated system Techniques ${TECHNAME} - automatically done by rudder-upgrade script" >/dev/null 2>&1
    # Schedule a Technique library reload later because of the update
    echo "INFO: A Technique library reload is needed and has been scheduled."
    touch /opt/rudder/etc/force_technique_reload
  fi
  # remove it in /opt/rudder/share/ so that subsequent rudder server upgrade-techniques don't put it back
  if [ -d ${INITTECHDIR} ]; then
    rm -rf ${INITTECHDIR}
  fi
}

# Helper function to compare version numbers with 2 components
ver() { printf "1%03d%03d" `echo "$1" | tr '.' ' '`; }


################################################################################
# Update credentials
################################################################################

# - All versions: Check if access credentials in rudder-web.properties match the ones from rudder-passwords.conf
# For every property file, check if the access credentials match between the property file and
# the rudder-passwords.conf file. If not, update the properties.
#
# This is to prevent an upgrade failure if the properties have been reset during a package upgrade.
update_credentials() {
  STEP="Update credentials"
  if [ -f /opt/rudder/etc/rudder-passwords.conf ]; then

    # Get the passwords stored in rudder-passwords.conf
    REFERENCE_LDAP_PASSWORD=$(grep -E "^RUDDER_OPENLDAP_BIND_PASSWORD:" /opt/rudder/etc/rudder-passwords.conf |cut -d ":" -f 2-)
    REFERENCE_SQL_PASSWORD=$(grep -E "^RUDDER_PSQL_PASSWORD:" /opt/rudder/etc/rudder-passwords.conf |cut -d ":" -f 2-)

    property_file="rudder-web.properties"
    echo -n "INFO: Checking if ${property_file} database access credentials are all right..."

    if [ ! -e /opt/rudder/etc/${property_file} ]; then echo " non existent, skipping"; return; fi

    # 1 - Check LDAP credentials on all property files

    # Get the LDAP password according to the property file
    PROPERTY_LDAP_PASSWORD=$(grep -E "^ldap.authpw[ \t]*=" /opt/rudder/etc/${property_file} |cut -d "=" -f 2-)
    if [ "z${REFERENCE_LDAP_PASSWORD}" = "z${PROPERTY_LDAP_PASSWORD}" ]; then
      echo -n " LDAP OK, "
    else
      sed -i "s%ldap.authpw[ \t]*=.*%ldap.authpw=${REFERENCE_LDAP_PASSWORD}%" /opt/rudder/etc/${property_file}
      LDAP_PASSWORD=${REFERENCE_LDAP_PASSWORD}
      # Need to restart rudder-slapd so that services can connect to it
      systemctl restart rudder-slapd
      echo -n " LDAP Credentials updated, "
    fi

    # 2 - SQL properties only apply to rudder-web.properties

    # Get the SQL password according to the property file
    PROPERTY_SQL_PASSWORD=$(grep -E "^rudder.jdbc.password[ \t]*=" /opt/rudder/etc/${property_file} |cut -d "=" -f 2-)
    if [ "${REFERENCE_SQL_PASSWORD}" = "${PROPERTY_SQL_PASSWORD}" ]; then
      echo " SQL OK"
    else
      # Credentials from the properties and the rudder-password.conf do not match, update the properties.
      sed -i "s%rudder.jdbc.password[ \t]*=.*%rudder.jdbc.password=${REFERENCE_SQL_PASSWORD}%" /opt/rudder/etc/${property_file}
      SQL_PASSWORD=${REFERENCE_SQL_PASSWORD}
      export PGPASSWORD="${SQL_PASSWORD}"
      echo " SQL Credentials updated"
    fi

  else
    echo "INFO: The /opt/rudder/etc/rudder-passwords.conf file is absent. LDAP and SQL passwords not checked in {rudder,inventory}-web.properties"
  fi
}

################################################################################
# Check git branch
################################################################################

# Before doing anything on git, set the branch to the Technique Reference Library branch
set_git_branch() {
  STEP="Set configuration repository branch"
  if [ -d ${CONFIGURATION_REPOSITORY}/.git ];then
    cd ${CONFIGURATION_REPOSITORY}/ && git checkout master 2>&1
  fi
}

################################################################################
# Update ncf and system techniques
################################################################################

# Upgrade system techniques from system directory
upgrade_system_techniques() {
  STEP="Upgrade system Techniques"

  update_rudder_repository_from_system_directory /opt/rudder/share/techniques/system/inventory/ techniques/system/inventory/
  update_rudder_repository_from_system_directory /opt/rudder/share/techniques/system/rudder-service-postgresql/ techniques/system/rudder-service-postgresql/
  update_rudder_repository_from_system_directory /opt/rudder/share/techniques/system/rudder-service-slapd/ techniques/system/rudder-service-slapd/
  update_rudder_repository_from_system_directory /opt/rudder/share/techniques/system/server-common/ techniques/system/server-common/
  update_rudder_repository_from_system_directory /opt/rudder/share/techniques/system/common/ techniques/system/common/
  update_rudder_repository_from_system_directory /opt/rudder/share/techniques/system/rudder-service-apache/ techniques/system/rudder-service-apache/
  update_rudder_repository_from_system_directory /opt/rudder/share/techniques/system/rudder-service-relayd/ techniques/system/rudder-service-relayd/
  update_rudder_repository_from_system_directory /opt/rudder/share/techniques/system/rudder-service-webapp/ techniques/system/rudder-service-webapp/

  STEP="Remove deprecated system Techniques"
  remove_system_technique_from_system_directory server-roles

  remove_system_technique_from_system_directory distributePolicy
}

# Upgrade techniques
upgrade_techniques() {
  STEP="Upgrade Techniques"

  /opt/rudder/bin/rudder server upgrade-techniques  --autoupdate-technique-library --during-upgrade

  # Migrate RudderUniqueID to the template format
  NB_RUDDER_UNIQUE_ID=$( (grep -Er --exclude="*.xml"  "[^\&]RudderUniqueID" /var/rudder/configuration-repository/techniques 2>/dev/null || true) | wc -l)
  if [ ${NB_RUDDER_UNIQUE_ID} -ne 0 ]; then
    echo -n "INFO: Enforcing that Techniques are using correct format"
    find ${CONFIGURATION_REPOSITORY}/techniques -type f \( ! -iname '*.xml' \) -print0 | xargs -0 sed -i "s/\([^&]\|^\)RudderUniqueID\([^&]\|$\)/\1\&RudderUniqueID\&\2/g"
    cd ${CONFIGURATION_REPOSITORY}/techniques && git add . >/dev/null 2>&1
    git commit -m "Upgrade Techniques to template format - automatically done by rudder-upgrade script" >/dev/null 2>&1
    # Schedule a Technique library reload later because of the update
    touch /opt/rudder/etc/force_technique_reload
    echo " Done"
  fi
}

# Upgrade ncf from ncf package
upgrade_ncf() {
  # All versions: Upgrade ncf
  STEP="Upgrade ncf"

  mkdir -p ${RUDDER_VAR}/ncf/common
  if [ -d ${RUDDER_NCF_SOURCE_DIRECTORY}/tree ]; then
    if ! diff -aur ${RUDDER_NCF_SOURCE_DIRECTORY}/tree/ ${RUDDER_VAR}/ncf/common/ >/dev/null 2>&1; then
      rsync --delete --ignore-times -rpgoq ${RUDDER_NCF_SOURCE_DIRECTORY}/tree/ ${RUDDER_VAR}/ncf/common/
    fi
  fi

  # Security check: Ensure techniques written from the Technique Editor are not world-readable
  if [ -x ${CONFIGURATION_REPOSITORY}/ncf/50_techniques ]; then
    chmod -R o-rwx ${CONFIGURATION_REPOSITORY}/ncf/50_techniques/
  fi

  # All Versions: Touch ncf_update_flag_file jetty will be restarted at the end of the script
  touch /opt/rudder/etc/force_ncf_technique_update

  # Handle the case where we have an existing local method and a common method with the same name
  # Display a warning and delete local method
  if [ -x ${CONFIGURATION_REPOSITORY}/ncf/30_generic_methods ]; then
    CURRENT="$(pwd)"
    cd "${CONFIGURATION_REPOSITORY}/ncf/30_generic_methods/"
    commit_needed=0
    for method in *.cf; do
      [ -f "${method}" ] || break
      if [ -f "${RUDDER_NCF_SOURCE_DIRECTORY}/tree/30_generic_methods/${method}" ]; then
        if git ls-files --error-unmatch ${method} >/dev/null 2>&1; then
          git rm "${method}" >/dev/null
          commit_needed=1
          echo "WARNING: The ${method} generic method was already present in local configuration, removing it."
        else
          mv "${method}" "${method}.disabled"
          echo "WARNING: The ${method} generic method was already present in local configuration and not in local repo, disabling it (renamed to ${method}.disabled)."
        fi
        rm -f ${RUDDER_VAR}/ncf/local/30_generic_methods/${method}
      fi
    done
    [ ${commit_needed} -eq 1 ] && git commit --allow-empty -q -m "Remove duplicate local methods - automatically done by rudder-upgrade script"
    cd ${CURRENT}
  fi


}

# Upgrade masterfiles
upgrade_masterfiles() {
  # We should have a masterfiles initialized from initial promises
  STEP="Upgrade masterfiles from initial promises"
  if [ -d "${RUDDER_SHARE}/initial-promises/" ]
  then
    mkdir -p "${RUDDER_VAR}/cfengine-community/masterfiles/"
    rsync --delete --ignore-times -rptgoq "${RUDDER_SHARE}/initial-promises/" "${RUDDER_VAR}/cfengine-community/masterfiles/"
  fi
}

################################################################################
# Check and update database
################################################################################

# Upgrade the PostgreSQL database
upgrade_database() {
  # All versions: Check that Rudder database is able to handle backslash
  STEP="All versions: Check that Rudder database is able to handle backslash"

  CHECK_BACKSLASH=$(${PSQL} -t -d ${SQL_DATABASE} -c "select '\\foo';" 2>/dev/null | grep -c "foo" || true)
  if [ ${CHECK_BACKSLASH} -ne 1 ]; then
    echo -n "INFO: Rudder database is not backslash compliant, fixing..."
    ${PSQL} -t -d ${SQL_DATABASE} -c "alter database rudder set standard_conforming_strings=true;" >/dev/null 2>&1
    echo " Done"
  fi

}

################################################################################
# Check and upgrade slapd.conf
################################################################################
upgrade_slapdconf() {

  STEP="Upgrade slapd configuration file"
  SLAPD_CONF="/opt/rudder/etc/openldap/slapd.conf"
  NEED_REINDEX=false

  # If user choose to replace configuration file, then /opt/rudder/etc/openldap/slapd.conf
  # already contains the index, but nothing reindexed slapd
  # We need to check for existence of slapd.conf.dpkg-old, its age, and if it contains index
  SLAPD_CONF_BKP="${SLAPD_CONF}.dpkg-old"
  if [ -f ${SLAPD_CONF_BKP} ]; then
    # if file exist, and is less than 1 hour old, check for index in it
    if [ $(($(date +%s) - $(stat -c '%Z'  ${SLAPD_CONF_BKP}))) -lt 3600 ]; then
      INDEX_BKP_COUNT=$(grep -c "^index\s*directiveId\s*eq" ${SLAPD_CONF_BKP} 2>/dev/null || true)
      INDEX_BKP_COUNT_2=$(grep -c "^index\s*modifyTimestamp\s*eq" ${SLAPD_CONF_BKP} 2>/dev/null || true)
      INDEX_BKP_COUNT_3=$(grep -c "^index\s*softwareId\s*eq" ${SLAPD_CONF_BKP} 2>/dev/null || true)
      if [ ${INDEX_BKP_COUNT} -eq 0 ] || [ ${INDEX_BKP_COUNT_2} -eq 0 ] || [ ${INDEX_BKP_COUNT_3} -eq 0 ]; then
        NEED_REINDEX=true
      fi
    fi
  fi

  if ${NEED_REINDEX}; then
    # stop slapd, slapindex -q, start slapd.
    systemctl stop rudder-slapd
    echo -n "Reindexing LDAP directory - this may take a few minutes..."
    su - rudder-slapd -s /bin/sh -c "/opt/rudder/sbin/slapindex"
    echo " Done"
    systemctl start rudder-slapd
  fi
}

################################################################################
# Check and upgrade plugins
################################################################################
upgrade_plugins() {
  # Don't restart, it is done at the end of the postinst
  export RUDDER_PACKAGE_DONT_RESTART=1
  # Don't run the postinst scripts as some require a running webapp.
  # It is done by the postinst script afterwards.
  export RUDDER_PACKAGE_DONT_RUN_POSTINST=1

  STEP="Upgrade all plugins"
  # Remove the user-management if exists as the feature is now builtin
  rudder package remove user-management 2>/dev/null
  # Remove the reporting plugin as it has been discontinued
  rudder package remove reporting 2>/dev/null
  # Remove the aix plugin as AIX support was dropped
  rudder package remove aix 2>/dev/null
  PLUGIN_STATUS_FILE="/tmp/rudder-plugins-upgrade"
  if rudder package update --check >/dev/null 2>&1 ; then
    rudder package update || true
    rudder package upgrade --all || true
  else
    echo "Plugins were not updated, because connection test is failing, please upgrade your plugins manually"
  fi

  if [ -f $PLUGIN_STATUS_FILE ]; then
    rudder package enable --restore < $PLUGIN_STATUS_FILE || true
    rudder package disable --incompatible || true

    # Finally, remove it
    rm $PLUGIN_STATUS_FILE
  fi
}

################################################################################
# Migration function calls
################################################################################

update_credentials
upgrade_slapdconf
set_git_branch
upgrade_system_techniques
upgrade_techniques
upgrade_ncf
upgrade_masterfiles

# Upgrade database
echo -n "INFO: Upgrading PostgreSQL DB..."
# if the server is localhost, try to start postgresql to ensure that database schema is upgraded
if [ "$SQL_SERVER" = "localhost" ]; then
  systemctl start $(systemctl --no-ask-password list-unit-files --type service | awk -F'.' '{print $1}' | grep -E "^postgresql-?[0-9]*$" | tail -n 1)
fi
if retry_wrapper "${PSQL} -t -d ${SQL_DATABASE} -c 'select 1' >/dev/null 2>&1" "PostgreSQL";
then
  echo " OK"
  upgrade_database
else
  echo " ERROR"
  INCOMPLETE_MIGRATION=true
fi

# Upgrade ldap properties
echo -n "INFO: Upgrading LDAP DB..."
# starting slapd because it is stopped during upgrade
systemctl start rudder-slapd

upgrade_plugins

################################################################################
# End
################################################################################

# For every upgrade, we force the root server to run a new inventory on the next CFEngine run
touch /opt/rudder/etc/force_inventory

echo ""
if ${INCOMPLETE_MIGRATION}
then
  echo "ERROR: The migration has failed in some steps. Check previous error messages."
  echo "Please restart the failed service(s), and start the migration script again."
  echo "(try service rudder-server restart)"
  echo "Once it is working, run:"
  echo "# /opt/rudder/bin/rudder-upgrade"
else
  echo "INFO: The migration has completed successfully."
fi
