#!/bin/bash

gcov --source-prefix @CMAKE_SOURCE_DIR@ --preserve-paths --relative-only $(find -iname *.gcda) 1>/dev/null || exit 0

if [ ! -z "${TRAVIS_JOB_ID}" ]
then

  cat >coverage.json <<EOF
{
  "service_name": "travis-ci",
  "service_job_id": "${TRAVIS_JOB_ID}",
  "run_at": "$(date --iso-8601=s)",
  "source_files": [
EOF

else

  cat >coverage.json <<EOF
{
  "repo_token": "$1",
  "run_at": "$(date --iso-8601=s)",
  "git": {
    "head": {
      "id": "$(git log -1 --pretty=format:%H)",
      "author_name": "$(git log -1 --pretty=format:%an | sed -re 's%\\%\\\\%g; s%"%\\"%g; s%$%\\n%' | tr -d $'\n' | sed -re 's%\\n$%%')",
      "author_email": "$(git log -1 --pretty=format:%ae | sed -re 's%\\%\\\\%g; s%"%\\"%g; s%$%\\n%' | tr -d $'\n' | sed -re 's%\\n$%%')",
      "committer_name": "$(git log -1 --pretty=format:%cn | sed -re 's%\\%\\\\%g; s%"%\\"%g; s%$%\\n%' | tr -d $'\n' | sed -re 's%\\n$%%')",
      "committer_email": "$(git log -1 --pretty=format:%ce | sed -re 's%\\%\\\\%g; s%"%\\"%g; s%$%\\n%' | tr -d $'\n' | sed -re 's%\\n$%%')",
      "message": "$(git log -1 --pretty=format:%B | sed -re 's%\\%\\\\%g; s%"%\\"%g; s%$%\\n%' | tr -d $'\n' | sed -re 's%\\n$%%')"
    },
    "branch": "$(git rev-parse --abbrev-ref HEAD)",
    "remotes": [
      $(git remote -v | grep 'fetch' | awk '{ print "{\"name\":\""$1"\",\"url\":\""$2"\"}" }' | tr $'\n' ',' | sed -re 's%,$%%')
    ]
  },
  "source_files": [
EOF

fi


for file in $(find * -iname '*.gcov' -print)
do
  srcname=$(echo ${file} | sed -re 's%#%\/%g; s%.gcov$%%')
  cat >>coverage.json <<EOF
    {
      "name": "${srcname}",
      "source": "$(tail -n +3 ${file} | cut -d ':' -f 3- | sed -re 's%\\%\\\\%g; s%"%\\"%g; s%\t%\\t%g; s%$%\\n%' | tr -d $'\n' | sed -re 's%\\n$%%')",
      "coverage": [$(tail -n +3 ${file} | cut -d ':' -f 1 | sed -re 's%^ +%%g; s%-([0-9]+)%\1%; s%-%null%g; s%^[#=]+$%0%;' | tr $'\n' ',' | sed -re 's%,$%%')]
    },
EOF
done

mv coverage.json coverage.json.tmp
cat >coverage.json <(head -n -1 coverage.json.tmp) <(echo -e "    }\n  ]\n}")
rm coverage.json.tmp

curl -F json_file=@coverage.json https://coveralls.io/api/v1/jobs

rm *.gcov
