#!{{ shell_binary }}
LC_ALL=C
export LC_ALL
umask 077

# Exit on any error, to prevent inconsistent backup
set -e

# Redirect output to log
exec > >(tee -ai {{ output_log_file }})
exec 2>&1

echo -e "\n\n$0 run at : $(date)"

srv_directory={{ directory['srv'] }}

sync_element () {
  path=$1
  backup_path=$2
  shift 2
  element_list=$*

  # Concatenate the exclude file of each partition of webrunner
  # to create a global exclude file.
  exclude_content="instance/supervisord.socket"
  for partition in $srv_directory/runner/instance/slappart*
  do
    exclude_file="$partition/srv/exporter.exclude"
    if [ -e "$exclude_file" ]; then
      partition_exclude_content_relative=$(cat "$exclude_file")
      # For every line of the local exclude file, add the absolute path
      for line in "$partition_exclude_content_relative"
      do
        if [ ! -z "$line" ]; then
          exclude_content="$exclude_content\ninstance/$(basename $partition)/$line"
       fi
      done
    fi
  done
  echo -e "$exclude_content" > $srv_directory/exporter.exclude

  for element in $element_list
  do
    echo "Changing current directory to $path."
    cd $path;
    if [ -f $element ] || [ -d $element ]; then
       command="{{ rsync_binary }} -rlptgov --stats --safe-links --exclude-from=$srv_directory/exporter.exclude --delete --delete-excluded $element  $backup_path"
       echo "Running : $command"
       $command
    fi
  done
}
sync_element $srv_directory/runner {{ directory['backup'] }}/runner/ instance project proxy.db
# We sync .* appart
date +%s -u > {{ directory['etc'] }}/.resilient-timestamp
sync_element {{ directory['etc'] }}  {{ directory['backup'] }}/etc/ config.json
# Hidden files are related to the webrunner's internals
cp -r {{ directory['etc'] }}/.??* {{ directory['backup'] }}/etc/
if [ -d {{ directory['backup'] }}/runner/software ]; then
  rm {{ directory['backup'] }}/runner/software/*
fi

cd {{ directory['backup'] }} && find -type f ! -name backup.signature -print0 | xargs -P4 -0 sha256sum | LC_ALL=C sort -k 66 > backup.signature
