#!/usr/bin/env bash

PROJECT_DB_FILE="/src/.tamarinrc"
GLOBAL_DB_FILE="${TAMARIN_WORKSPACE}/.tamarinrc"
KEY_PREFIX="tamarin_db_"

function tamarin_load_project_db {
  if [ -e "${PROJECT_DB_FILE}" ]; then
    tamarin_info "Loading project database..."
    while read line; do
      if [[ ! "${line}" =~ ^\s*# ]]; then
        set -- $(echo $line | tr '=' ' ')
        local key=$1
        local value=$2
        tamarin_debug "Load $key=$value"
        tamarin_db_set $key $value
      fi
    done < "${PROJECT_DB_FILE}"
  fi
}

function tamarin_db_get {
  local opt_name=${KEY_PREFIX}${1}
  local default_value=${@:2}
  touch "${GLOBAL_DB_FILE}"
  source "${GLOBAL_DB_FILE}"
  echo ${!opt_name:-${default_value}}
}

function tamarin_db_set {
  local opt_name=${1}
  local opt_value=${@:2}
  mkdir -p "$(dirname ${GLOBAL_DB_FILE})"
  touch "${GLOBAL_DB_FILE}"
  sed -i "s/^${KEY_PREFIX}${opt_name}*$//" "${GLOBAL_DB_FILE}"
  echo "local ${KEY_PREFIX}${opt_name}=\"${opt_value}\"" >> "${GLOBAL_DB_FILE}"
}

case $1 in
  set)
    tamarin_db_set ${@:2}
    ;;
  get)
    tamarin_db_get ${@:2}
    ;;
  load)
    tamarin_load_project_db
    ;;
  *)
    tamarin_error "Invalid action '$1'. Must be get, set or load !"
    exit 1
    ;;
esac