#!/bin/bash

cvmfs_test_name="Client configuration files and showconfig output"
cvmfs_test_suites="quick"

create_config_files() {
  sudo sh -c "echo CVMFS_KCACHE_TIMEOUT=2 > /etc/cvmfs/default.d/50-testA.conf" || return 1
  sudo sh -c "echo CVMFS_KCACHE_TIMEOUT=3 > /etc/cvmfs/default.d/50-testB.conf" || return 2
  sudo sh -c \
    "echo EESSI_HOST_INJECTIONS=/tmp/eessi/host_injections \
    > /etc/cvmfs/default.d/50-testC.conf" || return 3
  # These valid config names must not collide with showconfig's option state.
  sudo sh -c \
    "echo all_output=0 > /etc/cvmfs/default.d/50-testD.conf" || return 4
  sudo sh -c \
    "echo all_opt= > /etc/cvmfs/default.d/50-testE.conf" || return 5

  return 0
}

cleanup_config_files() {
  sudo rm -f /etc/cvmfs/default.d/50-test*
}

# Sort ';'- separated components within each value: some (e.g. CVMFS_PAC_URLS,
# randomized in cvmfs-config.cern.ch's default.conf because of $RANDOM) aren't guaranteed to
# keep a stable order across separate showconfig invocations.
sort_value_lists() {
  awk '{
    eq = index($0, "=")
    n = split(substr($0, eq + 1), v, ";")
    n = asort(v)
    val = v[1]
    for (i = 2; i <= n; i++) val = val ";" v[i]
    print substr($0, 1, eq) val
  }'
}

# Turn the plain 'showconfig' output into sorted KEY=VALUE lines: keep only
# parameter lines, dropping the "# from SOURCE" provenance and inverting the
# shell quoting that 'cvmfs2 -o parse' applies (EscapeShell in options.cc).
# A value that needs escaping is wrapped in single quotes with inner ' as \';
# for such a value we read up to the closing quote and un-escape, so the trailing
# "# from ..." (which lives outside the quotes) is dropped and the value is
# recovered verbatim. Unquoted values just have the provenance suffix stripped.
normalize_plain() {
  awk -v q="'" '
    /^[A-Za-z_][A-Za-z0-9_]*=/ {
      eq = index($0, "=")
      key = substr($0, 1, eq - 1)
      rest = substr($0, eq + 1)
      if (substr(rest, 1, 1) == q) {
        value = ""; i = 2; n = length(rest)
        while (i <= n) {
          c = substr(rest, i, 1)
          if (c == "\\" && substr(rest, i + 1, 1) == q) { value = value q; i += 2; continue }
          if (c == q) break
          value = value c; i++
        }
      } else {
        value = rest
        sub(/[ \t]+# from .*$/, "", value)
      }
      print key "=" value
    }
  ' | sort_value_lists | sort
}

# Turn a 'showconfig -j' object into the same sorted KEY=VALUE lines.
normalize_json() {
  jq -r 'to_entries[] | "\(.key)=\(.value)"' | sort_value_lists | sort
}

cvmfs_run_test() {
  logfile=$1

  local retval=0
  create_config_files || retval=1

  cvmfs_mount grid.cern.ch || retval=2
  sudo cvmfs_talk -i grid.cern.ch parameters | grep CVMFS_KCACHE_TIMEOUT=3 | grep /etc/cvmfs/default.d/50-testB.conf || retval=3
  cvmfs_config showconfig grid.cern.ch | grep CVMFS_KCACHE_TIMEOUT=3 | grep /etc/cvmfs/default.d/50-testB.conf || retval=4

  # The JSON output (-j) must expose the same resolved configuration as the
  # plain text output.
  # the value resolved above must also appear in the JSON object
  cvmfs_config showconfig -j grid.cern.ch | jq -e '.CVMFS_KCACHE_TIMEOUT == "3"' > /dev/null || retval=40
  # the JSON object carries the same parameters as the plain output
  diff <(cvmfs_config showconfig    grid.cern.ch | normalize_plain) \
       <(cvmfs_config showconfig -j grid.cern.ch | normalize_json) || retval=41
  # the short output (-s) is identical in plain and JSON form
  diff <(cvmfs_config showconfig -s   grid.cern.ch | normalize_plain) \
       <(cvmfs_config showconfig -s -j grid.cern.ch | normalize_json) || retval=42
  # without a repository name the output is a JSON array, one object per repo
  diff <(cvmfs_config showconfig    | normalize_plain) \
       <(cvmfs_config showconfig -j | jq '.[]' | normalize_json) || retval=43

  # Check that the environment variable CVMFS_USE_CDN is not leaked into the JSON and plain output
  local leaked="shell_leak_sentinel"
  [ "$(CVMFS_USE_CDN=$leaked cvmfs_config showconfig -j grid.cern.ch \
         | jq -r '.CVMFS_USE_CDN')" = "$leaked" ] && retval=44
  CVMFS_USE_CDN=$leaked cvmfs_config showconfig grid.cern.ch \
    | grep -q "^CVMFS_USE_CDN=$leaked" && retval=45

  # grid.cern.ch is a repository that has 4 server urls, separated by ';' so we check that the JSON output
  # does not contain any single quotes put by EscapeShell()
  cvmfs_config showconfig -j grid.cern.ch \
    | jq -e "(.CVMFS_SERVER_URL // \"\") | test(\"'\") | not" >/dev/null \
    || retval=46

  # A repository mountpoint must resolve like the repository name in both
  # output formats.
  local plain_by_name plain_by_path plain_by_path_slash plain_by_name_slash
  local json_by_name json_by_path line mount_dir
  local short_by_name short_by_path
  plain_by_name=$(cvmfs_config showconfig grid.cern.ch) || retval=47
  while read -r line; do
    if [[ "$line" == CVMFS_MOUNT_DIR=* ]]; then
      mount_dir=${line#CVMFS_MOUNT_DIR=}
      break
    fi
  done < <(printf '%s\n' "$plain_by_name" | normalize_plain)
  if [[ -z "$mount_dir" ]]; then
    retval=48
    mount_dir=/cvmfs
  fi

  plain_by_path=$(cvmfs_config showconfig \
    "${mount_dir%/}/grid.cern.ch") || retval=49
  diff <(printf '%s\n' "$plain_by_name" | normalize_plain) \
       <(printf '%s\n' "$plain_by_path" | normalize_plain) || retval=50
  grep -q '^CVMFS_REPOSITORY_NAME=grid.cern.ch$' \
    <<< "$plain_by_path" || retval=51
  plain_by_path_slash=$(cvmfs_config showconfig \
    "${mount_dir%/}/grid.cern.ch/") || retval=52
  diff <(printf '%s\n' "$plain_by_name" | normalize_plain) \
       <(printf '%s\n' "$plain_by_path_slash" | normalize_plain) \
       || retval=53
  plain_by_name_slash=$(cvmfs_config showconfig grid.cern.ch/) || retval=54
  diff <(printf '%s\n' "$plain_by_name" | normalize_plain) \
       <(printf '%s\n' "$plain_by_name_slash" | normalize_plain) \
       || retval=55

  json_by_name=$(cvmfs_config showconfig -j grid.cern.ch) || retval=56
  json_by_path=$(cvmfs_config showconfig -j \
    "${mount_dir%/}/grid.cern.ch") || retval=57
  diff <(printf '%s\n' "$json_by_name" | normalize_json) \
       <(printf '%s\n' "$json_by_path" | normalize_json) || retval=58
  jq -e '.CVMFS_REPOSITORY_NAME == "grid.cern.ch"' \
    <<< "$json_by_path" >/dev/null || retval=59

  short_by_name=$(cvmfs_config showconfig -s grid.cern.ch) || retval=60
  short_by_path=$(cvmfs_config showconfig -s \
    "${mount_dir%/}/grid.cern.ch") || retval=61
  diff <(printf '%s\n' "$short_by_name" | normalize_plain) \
       <(printf '%s\n' "$short_by_path" | normalize_plain) || retval=62

  expect_exit_code 1 cvmfs_config showconfig \
    "${mount_dir%/}/grid.cern.ch/subdir" || retval=63
  expect_exit_code 1 cvmfs_config showconfig \
    /tmp/grid.cern.ch || retval=64

  # Non-CVMFS parameters are hidden by default and shown only on request.
  local variant_name=EESSI_HOST_INJECTIONS
  local variant_value=/tmp/eessi/host_injections
  local all_plain all_json short_all_plain short_all_json
  local recursive_all_plain recursive_all_json
  grep -q "^${variant_name}=" <<< "$plain_by_name" && retval=65
  jq -e --arg key "$variant_name" 'has($key) | not' \
    <<< "$json_by_name" >/dev/null || retval=66

  all_plain=$(cvmfs_config showconfig -a grid.cern.ch) || retval=67
  grep -q "^${variant_name}=${variant_value}$" \
    <<< "$(printf '%s\n' "$all_plain" | normalize_plain)" || retval=68
  all_json=$(cvmfs_config showconfig --all -j grid.cern.ch) || retval=69
  jq -e --arg value "$variant_value" \
    '.EESSI_HOST_INJECTIONS == $value' \
    <<< "$all_json" >/dev/null || retval=70
  jq -e '.all_output == "0" and .all_opt == ""' \
    <<< "$all_json" >/dev/null || retval=71
  diff <(printf '%s\n' "$all_plain" | normalize_plain) \
       <(printf '%s\n' "$all_json" | normalize_json) || retval=72

  short_all_plain=$(cvmfs_config showconfig -s -a grid.cern.ch) \
    || retval=73
  short_all_json=$(cvmfs_config showconfig --all -s -j grid.cern.ch) \
    || retval=74
  jq -e --arg value "$variant_value" \
    '.EESSI_HOST_INJECTIONS == $value' \
    <<< "$short_all_json" >/dev/null || retval=75
  diff <(printf '%s\n' "$short_all_plain" | normalize_plain) \
       <(printf '%s\n' "$short_all_json" | normalize_json) || retval=76

  recursive_all_plain=$(cvmfs_config showconfig -a) || retval=77
  grep -q "^${variant_name}=${variant_value}$" \
    <<< "$(printf '%s\n' "$recursive_all_plain" | normalize_plain)" \
    || retval=78
  recursive_all_json=$(cvmfs_config showconfig --all -j) || retval=79
  jq -e --arg value "$variant_value" '
    .[] | select(.CVMFS_REPOSITORY_NAME == "grid.cern.ch")
    | .EESSI_HOST_INJECTIONS == $value
  ' <<< "$recursive_all_json" >/dev/null || retval=80

  cvmfs_umount grid.cern.ch || retval=5

  cvmfs_mount grid.cern.ch "CVMFS_KCACHE_TIMEOUT=4" || retval=6
  sudo cvmfs_talk -i grid.cern.ch parameters | grep CVMFS_KCACHE_TIMEOUT=4 | grep /etc/cvmfs/default.local || retval=7
  cvmfs_config showconfig grid.cern.ch | grep CVMFS_KCACHE_TIMEOUT=4| grep /etc/cvmfs/default.local || retval=8
  cvmfs_umount grid.cern.ch || retval=9

  sudo mv /etc/cvmfs/default.d/50-testB.conf    /etc/cvmfs/default.d/50-testB.conf.disbled || retval=10

  cvmfs_mount grid.cern.ch || retval=20
  sudo cvmfs_talk -i grid.cern.ch parameters | grep CVMFS_KCACHE_TIMEOUT=2 | grep /etc/cvmfs/default.d/50-testA.conf || retval=21
  cvmfs_config showconfig grid.cern.ch | grep CVMFS_KCACHE_TIMEOUT=2 | grep /etc/cvmfs/default.d/50-testA.conf || retval=22
  cvmfs_umount grid.cern.ch || retval=23

  cleanup_config_files
  return $retval
}
