#!/bin/bash

FORGELIB_DOCKER_IMAGE=forge.3gpp.org:5050/tools/3gpp-scripts/forgelib:v2.10.0-bis
GENERATE_CHANGEMARKS_DOCKER_IMAGE=generatechangemarks:newCoversheet
DOCKER_IMAGE=pandoc/core:3.1.1.0

echo "\n------ Checking for docker image --------"
docker pull "$DOCKER_IMAGE"

echo "------ Removing previous outputs --------"
rm **/*.docx
rm out/*.md

echo "------ Parsing repo URL --------"

HOST_URL=$(echo $1 | cut -d'/' -f 1-3)
PROJECT_NAME=$(echo $1 | cut -d'/' -f 6- | cut -d'.' -f 1)
echo "HOST URL:" $HOST_URL
echo "PROJECT NAME:" $PROJECT_NAME
echo "PROJECT ID:" $2
echo "MERGE IID:" $3

echo "\n------ Generating change marks MD --------"
#docker container run --rm -v $(pwd):/tmp/ "$DOCKER_IMAGE" forgelib-changedocs -vv --combine --diffs --preprocessor onem2m --outPath=/tmp/docs --startdelimiter "/tmp/$4" --enddelimiter "/tmp/$5" --coversheet "/tmp/$6" "$HOST_URL" "$2" "$PROJECT_NAME" "$3"
docker container run --rm -v $(pwd):/tmp/ -u $(id -u):$(id -g) "$GENERATE_CHANGEMARKS_DOCKER_IMAGE" changemarks -o "/tmp/out" "$HOST_URL" "$2" "$3"

echo "\n------ Generating changemarks docx --------"
for i in out/*.md ;  do
    DOCUMENT_NAME=$(echo $i | cut -d'/' -f 2)
	echo "\n------ Preparaing spec --------" 
	docker run --rm -v $(pwd):/tmp/ -u $(id -u):$(id -g) "$GENERATE_CHANGEMARKS_DOCKER_IMAGE" pandocFilter -o "/tmp/out" "/tmp/$i"
	echo "\n------ Publishing spec --------" 
	docker run --rm -v $(pwd):/data -u $(id -u):$(id -g) "$DOCKER_IMAGE" "/data/$i" -f markdown -t docx --reference-doc "Spec-template.docx" -o "/data/out/${DOCUMENT_NAME}.docx"
    #docker run --rm -v $(pwd):/data -u $(id -u):$(id -g) "$DOCKER_IMAGE" "/data/$i" -f markdown -t html -o "/data/out/${DOCUMENT_NAME}.html"
    #docker run --rm -v $(pwd):/data -u $(id -u):$(id -g) "$DOCKER_IMAGE" "/data/out/${DOCUMENT_NAME}.html" -f html -t docx --reference-doc "Spec-template.docx" -o "/data/out/${DOCUMENT_NAME}.docx"
done

echo "\n------ Combining docx --------"
#docker container run --rm -v $(pwd):/tmp/ -u $(id -u):$(id -g) "$FORGELIB_DOCKER_IMAGE" forgelib-changedocs -vv -sf "/tmp/out/" --preprocessor onem2m --outPath=/tmp/docs --startdelimiter "/tmp/$4" --enddelimiter "/tmp/$5" --coversheet "/tmp/$6" "$HOST_URL" "$2" "$3"
docker container run --rm -v $(pwd):/tmp/ -u $(id -u):$(id -g) -w "/tmp" "$FORGELIB_DOCKER_IMAGE" forgelib-changedocs -vv -sf "out/" --preprocessor onem2m --outPath=docs/ --startdelimiter "$4" --enddelimiter "$5" --coversheet "$6" "$HOST_URL" "$2" "$3"

echo "\n------ Converting to tracked changes docx --------"
for i in docs/*.docx ; do
    DOCUMENT_NAME=$(echo $i | cut -d'/' -f 2)
	docker container run --rm -v $(pwd):/tmp/ -u $(id -u):$(id -g) "$GENERATE_CHANGEMARKS_DOCKER_IMAGE" addTrackedChanges -o "/tmp/docs/$DOCUMENT_NAME" "/tmp/$i" "$HOST_URL" "$2" "$3"
done

exit 0
