#!/bin/bash

# Script to generate a formatted table of version that can be added to a redmine wiki page.
# 
# Each CCI release should have an accompanying wiki page at
#
#   https://redmind.dataone.org/projects/d1/wiki/CCI-XYZ
#
# where:
#   X = major version
#   Y = minor version
#   Z = patch version
#
# When a new tag is made of d1_stable_build_control, please add the table generated by this
# script to the wiki page. This will help keep track of which versions of each
# component are included with a CCI release.
#
# The script can be run in the same folder as current_release_control.properties or optionally
# a file path or URL may be provided as the first parameter. For example:
#
#   $ ./prop2redmine "https://repository.dataone.org/software/cicore/tags/D1_STABLE_BUILD_CONTROL_v2.2.5/current_release_control.properties"
#
# ---
# Notes:
#   Redmine formatting: http://www.redmine.org/projects/redmine/wiki/RedmineTextFormattingTextile
# ---

f_tmp=""
f_properties="${1}"
if [[ -z "${f_properties}" ]]; then
  f_properties="current_release_control.properties"
fi
if [[ "${f_properties}" == https://* ]]; then
  #download to a temporary file
  f_tmp=$(mktemp)
  curl -s -k "${f_properties}" > ${f_tmp}
  f_properties="${f_tmp}"
fi

k="Component"
v="Version"
plink="Tag"
printf "|_. %-28s |_. %-8s |_. %s |\n" "${k}" "${v}" "${plink}"
while read -r line; do
  if [[ "${line}" == "#"?evel* ]]; then
    v="${line#* }"
    # Uncomment next line to add build level entry
    #printf "|((. *Level %s* |  |  |\n" "${v:0:1}"
    continue
  else
    [[ "${line}" =~ ^#.*$ ]] && continue
  fi
  k="${line%=*}"
  v="${line#*_v}"
  vpath="${line#*=}"
  if [[ ! -z "${k}" ]]; then
    if [[ "${k}" == "CCI_TARGET" ]]; then
      plink=$(printf "\"%s\":/projects/d1/repository/show/tags/D1_STABLE_BUILD_CONTROL_v%s" "${vpath}" "${v}")
    else
      plink=$(printf "\"%s\":/projects/d1/repository/show/%s" "${vpath#*/}" "${vpath}")
    fi
    pcomponent="[[${k}]]"
    printf "| %-30s |=. %-10s | %s |\n" "${pcomponent}" "${v}" "${plink}"
  fi
done < ${f_properties}
if [[ ! -z "${f_tmp}" ]]; then
  rm "${f_tmp}"
fi