#!/usr/bin/env bash
#
# duplicate-sample.sh
#
function init_duplicate {
  declare -g _entries_json_='{}'
}

function add_for_duplicate {
  local -r _key_="$1"
  local -r _id_="$2"

  _entries_json_="$(
    jq -c --arg key "${_key_}" --arg id "${_id_}" '.[$key] |= .+ [ $id ]' <<<"${_entries_json_}"
    )" || return $?
}

function finalize_duplicate {
  _entries_json_="$(
    jq '[ to_entries[] | select( .value | length >1 ) ] | from_entries' <<<"${_entries_json_}"
    )" || return $?
}

function display_current_result {
  jq '.' <<<"${_entries_json_}" || return $?
}

function main {
  init_duplicate || return $?

  add_for_duplicate 'k1' 'v1-1' || return $?
  add_for_duplicate 'k1' 'v1-2' || return $?
  add_for_duplicate 'k2' 'v1-2' || return $?
  add_for_duplicate 'k2' 'v2-2' || return $?
  add_for_duplicate 'k3' 'v3-1' || return $?

  echo 'Résultat complet'
  display_current_result || return $?

  finalize_duplicate || return $?

  echo 'Résultat contenant les doubles'
  display_current_result || return $?
}

main "$@" || exit $?
