#!/bin/sh -Cefu


set -Cefu


cd /home/ketas/files/astra || exit 1


whole_page_title="`cat tpl/whole-page-title.txt`"


_replace_with_file()
{
	local template="$1"
	local file="$2"
	
	
	sed -e "/$template/ { r $file" -e 'd; }'
}


_replace()
{
	local template="$1"
	local string="$2"
	
	
	sed "s|$template|$string|g"
}


_prepare_page()
{
	local whole_page_title="$1"
	
	
	_replace %_whole_page_title_% "$whole_page_title" < tpl/page.html \
	| _replace_with_file %_css_import_% tpl/import.css \
	| _replace_with_file %_css_styles_% tpl/styles.css
}


_sane_urlpart()
{
	local urlpart="$1"
	
	
	echo -n "$urlpart" | tr '[:upper:]' '[:lower:]' | tr -c a-z0-9 -
}


_src_time_tag()
{
	local file="$1"
	
	
	stat -t '[%s] %F %T %z/%Z' -f 'created %SB, modified %Sm' "$file"
}


_build_entry()
{
	local fullpath="$1"
	
	local dir="${fullpath%/*}"
	local file="${fullpath##*/}"
	local file_without_extension="${file%.*}"
	
	local date="${dir##*/}"
	local urlpart="`_sane_urlpart \"$file_without_extension\"`"
	local title="`echo -n \"$file_without_extension\" | tr - ' '`"
	
	local whole_page_title="$title - $whole_page_title [$date]"
	
	local input="$fullpath"
	local output="$dir/.$urlpart.html"
	
	local mtime="`_src_time_tag \"$input\"`"
	
	local mtime_log="`stat -t '%F %T %z' -f %Sm \"$input\"`"
	
	
	printf '%s %30s %s\n' "$date" "$urlpart" "$mtime_log"
	
	
	rm -f "$output.tmp" tmp/entry tmp/entry-part
	
	#fold -s "$input" > tmp/entry-part
	cat "$input" > tmp/entry-part
	
	_replace %_date_% "$date" < tpl/entry.html \
	| _replace %_title_% "$title" | _replace %_mtime_% "$mtime" \
	| _replace_with_file %_entry_% tmp/entry-part > tmp/entry
	
	_prepare_page "$whole_page_title" \
	| _replace_with_file %_main_% tmp/entry > "$output.tmp"
	
	mv "$output.tmp" "$output"
	
	rm -f tmp/entry tmp/entry-part
	
	_replace %_date_% "$date" < tpl/list-part.html \
	| _replace %_urlpart_% "$urlpart" | _replace %_title_% "$title" \
	>> tmp/list-part
}


rm -f root/index.html.tmp tmp/list tmp/list-part

touch tmp/list-part

find entries -depth 1 | sort -r | while read dir
do
	find "$dir" -not -name '.*' -name '*.html' | xargs stat -f '%m %N' \
	| sort -r | cut -d ' ' -f 2 | while read file
	do
		_build_entry "$file"
	done
done

_replace_with_file %_list_% tmp/list-part < tpl/list.html > tmp/list

_prepare_page "$whole_page_title" | _replace_with_file %_main_% tmp/list \
> root/index.html.tmp

mv root/index.html.tmp root/index.html

rm -f tmp/list tmp/list-part
