#!/usr/bin/env bash

# Set magic variables for current file, directory, os, etc.
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
__file="${__dir}/$(basename "${BASH_SOURCE[0]}")"
__base="$(basename ${__file} .sh)"
source "${__dir}/_b3bp.sh"

function fetch_protocol {
  local url=$1
  local slug=$2
  local outdated=$3

  local settings=""

  # The pages of old protocol versions should not contains comments
  # and should not be indexed by search engines.
  if [ "${outdated}" == "1" ]
  then
    settings="version_outdated: true"
  else
    settings="version_outdated: false"
  fi

  echo "--> Fetching protocol ${slug}"

  # Removes first two lines to allow our own h2 header
  local content
  content="$(curl --silent --fail --retry 3 "${url}" | tail -n +3)"

  cat <<EOF > "${__dir}/../src/content/protocols/${slug}.md"
---
# This file is generated by _scripts/inject-protocol.sh. Do not modify it manually!
title: Resumable upload protocol ${slug}
description: "The tus protocol specification: Detailing the interactions between tus clients and servers for reliable and resumable file uploads."
version: ${slug}
${settings}
---

## Table of Contents

## About this version

${content}
EOF
}

fetch_protocol "https://raw.githubusercontent.com/tus/tus-resumable-upload-protocol/main/protocol.md" "1.0.x" 0
fetch_protocol "https://raw.githubusercontent.com/tus/tus-resumable-upload-protocol/0.2/protocol.md" "0.2.x" 1
fetch_protocol "https://raw.githubusercontent.com/tus/tus-resumable-upload-protocol/0.1/README.md" "0.1.x" 1
