#!/bin/bash
# This script allow to update the list of folders included in
# backup-manager backups.
# It is a little command line help to ease administration tasks.

NAME=$(basename $0);
COMMAND=$1;

# We remove the command from the $@ arguments list.
shift

usage() {
  echo "Usage:

    ${NAME} [ add | remove ] /my/folder [ /my/other/folder ] ...

    * add /my/folder
      Used with the add action, this tool add the given folders to the list of
      folders included in the backup-manager backups.
    * remove /my/folder
      Used with the remove action this tool remove the given folders from the
      list of folders included in the backup-manager backups.
      
    This tool needs backup-manager to be installed and configured."

  exit 3
}


remove_path() {
  REMOVED_FOLDER=$1
  sed -i -e "s|\(.*BM_TARBALL_DIRECTORIES=\"\)${REMOVED_FOLDER} \(.*\)$|\1\2|" \
         -e "s|\(.*BM_TARBALL_DIRECTORIES=\".* \)${REMOVED_FOLDER} \(.*\)$|\1\2|" \
         -e "s|\(.*BM_TARBALL_DIRECTORIES=\".*\) ${REMOVED_FOLDER}\(\".*\)$|\1\2|" \
         -e 's| [ ]*| |g' \
      /etc/backup-manager.conf
}


# We test that there is at least something to add:
if [ $# -eq 0 ]; then
  usage
fi


case "${COMMAND}" in
  add)
    for FOLDER in $@; do
      if [ -e "${FOLDER}" ]; then
        FULL_PATH_FOLDER=$(readlink -f "${FOLDER}")

        # We remove the path from current backuped folder list to avoid duplicata
        remove_path "$FULL_PATH_FOLDER"

        # And we add it again:
        sed -i -e "s|\(.*BM_TARBALL_DIRECTORIES=\".*\)\(\".*\)$|\1 ${FULL_PATH_FOLDER}\2|" \
               -e 's| [ ]*| |g' \
            /etc/backup-manager.conf
      else
        echo "- ${FOLDER} does not exists or is not a folder."
      fi
    done
    ;;
  remove)
    for FOLDER in $@; do
      if [ -d "${FOLDER}" ]; then
        FULL_PATH_FOLDER=$(readlink -f "${FOLDER}")

        # We remove the path from current backuped folder list to avoid duplicata
        remove_path "$FULL_PATH_FOLDER"
      else
        # We can not find the folder, but may be it does not exists anymore.
        # We try to remove it.
        remove_path "${FOLDER}"
      fi
    done
    ;;
  *)
    usage
    ;;
esac

