#!/bin/sh

SNIPPET_REPO=/var/lib/jenkins/snippets
SNIPPET_ROOT=system/configs
LOCK_FILE=/run/elektra-update-snippet-repository.lock
KEY_SLASH_REPLACED=$(echo "$ELEKTRA_REST_KEY" | tr '/' '_')

export_snippets() {
  kdb export "$SNIPPET_ROOT/$ELEKTRA_REST_KEY" ni > "ni/$KEY_SLASH_REPLACED.ini"
  kdb export "$SNIPPET_ROOT/$ELEKTRA_REST_KEY" ini > "ini/$KEY_SLASH_REPLACED.ini"
  kdb export "$SNIPPET_ROOT/$ELEKTRA_REST_KEY" xmltool > "xmltool/$KEY_SLASH_REPLACED.xml"
  kdb export "$SNIPPET_ROOT/$ELEKTRA_REST_KEY" yajl > "yajl/$KEY_SLASH_REPLACED.json"
}

push_changes_to_git() {
  git add snippets.dump
  git add "ni/$KEY_SLASH_REPLACED.ini"
  git add "ini/$KEY_SLASH_REPLACED.ini"
  git add "xmltool/$KEY_SLASH_REPLACED.xml"
  git add "yajl/$KEY_SLASH_REPLACED.json"

  case "$ELEKTRA_REST_ACTION" in
    "INSERT")
      action=added
      ;;
    "UPDATE")
      action=updated
      ;;
    "DELETE")
      action=deleted
      ;;
    *)
      action=changed
      ;;
  esac

  git commit -m "auto-commit: $ELEKTRA_REST_AUTHOR $action entry $ELEKTRA_REST_KEY" -m "$(printf "Title: %s\nPlugin: %s\n" $ELEKTRA_REST_TITLE $ELEKTRA_REST_PLUGIN)"
  git push
}

(
  flock -x 9

  cd $SNIPPET_REPO || exit 1
  export_snippets
  push_changes_to_git
) 9>$LOCK_FILE
