#!/usr/bin/env bash

#==============================================================================
# Section Generator for Info Processing Class's Assignment.
#
# $1 = Directory to program information(info.json)
#
# With following directory structure for programs, it will generate the LaTeX
# section that contains assignment description, code listing, and execution
# result:
# |-programs
#   |-prog1
#   | |-example.h        // included
#   | |-main.c           // included
#   | |-Makefile         // excluded
#   | |-info.json
#   ...
#
# For each program directory, it must contain file named "info.json" which
# contains assignment name, description, type of output(screenshot, list of 
# values, or text file), and optional note.
#
# JSON scheme:
# {
#   "name": "<Name of Assignment>",
#   "description": "<Description of Assignment>",
#   "output": {
#     "type": "<screenshot | text",
#     "content":
#       "<path to screenshot or text file relative to $2>"
#   },
#   "note": "<Nullable string>"
# }
#
# The output LaTeX section is written to stdout
#==============================================================================

progPath=""

function writeSection () {
    local programDirectory="$1"
    local jsonFile="$programDirectory/info.json"
    local sectionName="$(jq --raw-output '.name' $jsonFile)"
    local description="$(jq --raw-output '.description' $jsonFile)"
    local outType="$(jq --raw-output '.output.type' $jsonFile)"
    local outContent="$(jq --raw-output '.output.content' $jsonFile)"
    local note="\n\n$(jq --raw-output '.note' $jsonFile)"
    declare -a listings
    local i=0
    local x=0
    local res=""

    [[ $note == "\n\nnull" || $note == "\n\n" ]] && note=""

    res+="\\section{$sectionName}\n\n$description\n\n\\subsection{コードリスティング}\n\n"

    for f in $(find $programDirectory -name '*.py' -or -name '*.c' -or -name '*.h'); do
        listings[i]="\\lstinputlisting[language=,title={$sectionName}]{../$f}"
        i=$(($i+1))
    done

    while [[ $x -lt $i ]]; do
        res+="$(echo -e "${listings[x]}")\n"
        x=$(($x+1))
    done

    res+="\n\\subsection{実行結果}\n"

    if [[ $outType == "screenshot" ]]; then
        res+="\n\\\\begin{center}\n    \\includegraphics[width=\\\\textwidth]{$outContent}\n\\\\end{center}"
    elif [[ $outType == "text" ]]; then
        res+="\n\\\\verbatiminput{$outContent}";
    else
        echo "Invalid Output Type: $outType";
        exit 1;
    fi

    if [[ $note != "" ]]; then
	res+="\n\\subsection{考察}\n"
    	res+="$note"
    fi

    echo -e $res
}

if [[ -n $1 ]]; then
    progPath="$1"
else
    echo "No Arguments Provided"
    exit 1
fi

writeSection $progPath
