#!/bin/bash

# This is a stripped down version of the original publishing script that
# is only designed for the introductory material. It will publish files in
# the following manner:
#
# - All .md files are ignored.
# - All .shtml files are assumed to contain raw HTML without headers and
#   footers, so these are added, and the result is converted to Latin-1.
# - All other files are copied as is.
#
# Please note that .md files are outdated and should be ignored. Content is
# only in SHTML files.

SRC='.'
#DST='/wwwkurs/TDDE23/course_content'
DST='/www/ida/kurs/TDDE23/course_content'

FILENAME_REGEX="(.*\/)([^\/]+)\.(\w+)"

# Add local header and footer
function handle_html {
    local raw_html=$1

    local ida_header="<!-- Automatically constructed from another HTML file. Do not edit manually! -->
    <!--#include virtual=\"/~TDDE23/include/defaults.sv.shtml\" -->
    <!--#include virtual=\$PAGE_HEADER -->
    "

    local ida_footer="<!--#include virtual=\"\$PAGE_FOOTER\" -->"

    local html_content="${ida_header}${raw_html}${ida_footer}"

    iconv -f UTF-8 -t LATIN1 <<< "${html_content}"
}

# Write $content to a file at $destination/$filename
function write_structured {
    local filename=$1
    local content=$2
    local destination=$3

    destination_path="$destination/$filename"

    # Create directory if it doesn't exist
    mkdir -p "$(dirname \"$destination_path\")"

    # Write content to a temporary file that is copied to the destination
    echo "$content" > /tmp/publish_buffer
    cp /tmp/publish_buffer "$destination_path"
    chmod a+r "$destination_path"
    rm /tmp/publish_buffer
}

    
all_files=$(find "$SRC" -type f)
if [ ! "$all_files" == "" ]; then
   for file in $all_files; do
       filetype=$(echo "$file" | perl -pe "s|$FILENAME_REGEX|\3|")
       case "$filetype" in
       	    md)
		# Ignore .md files
		echo "#IGNORE $file"
	  	;;
       	    shtml)
                # Process .shtml files by adding header and footer
		echo "#PROCESS $file"
                file_content=$(cat "$file")
		output_content=$(handle_html "$file_content")
		echo "# Writing to file: ${DST}/${file}"
		write_structured "$file" "$output_content" "$DST"
                ;;
       	    *)
		# Copy all other files
		echo "#COPY $file"
		echo "cp $file ${DST}/${file}"
		cp "$file" "${DST}/${file}"
		chmod a+r "${DST}/${file}"
       esac
   done
fi

