#!/opt/homebrew/bin//bash

links=$(cat kozem.xml |grep -E '(chapter|section) id'|awk 'BEGIN{chapter=0; section=0}{split($0,a,"\""); if ($1 ~ /chapter/){section=0; chapter++; chapterref=a[2]; print "<link ref=\""a[2]"\">"chapter". "a[4]"</link>"}else{section++; print "<link indent=\"8\" ref=\""chapterref":"a[2]"\">"chapter"."section". "a[4]"</link>"}}'|awk 'BEGIN{i=1}{if (i==1){i++; myvar="            "$0}else{myvar=myvar"\\n            "$0}}END{sub(/\n/,"",myvar); print myvar}')
sed -i '/<link indent/d' kozem.xml
sed -i '/<link ref/d' kozem.xml

sed -i 's@<title>Index</title>@<title>Index</title>\n'"${links}"'@' kozem.xml


homeDir=~/stuff/sandbox/kozem_mods/minecraft/resources/torgobooks/textures/
grep '<image' kozem.xml |while read line; do
  if (echo "${line}"|grep -q animated); then
    imageFile=$(echo "${line}"|awk -vhomeDir="${homeDir}" '{gsub("torgobooks:", homeDir"/", $0); split($0, a, "\""); for (i in a) { if (a[i] ~ "src="){gsub(/\/1_.*/, "", a[i+1]); gsub(a[i+1], a[i+1]"/1.png", a[i+1]); print a[i+1]; break}}}')
  else
echo "${line}"
echo "${line}"|awk -vhomeDir="${homeDir}" '{gsub("torgobooks:", homeDir"/", $0); split($0, a, "\""); for (i in a) { if (a[i] ~ "src="){gsub(a[i+1], a[i+1]".png", a[i+1]); print a[i+1]; break}}}'
    imageFile=$(echo "${line}"|awk -vhomeDir="${homeDir}" '{gsub("torgobooks:", homeDir"/", $0); split($0, a, "\""); for (i in a) { if (a[i] ~ "src="){gsub(a[i+1], a[i+1]".png", a[i+1]); print a[i+1]; break}}}')
  fi
  if [[ -e "${imageFile}" ]]; then
    twstring=$(identify -format "tw=\"%w\" th=\"%h\"\n" "${imageFile}")
    echo identify -format "%w\n" "${imageFile}"
    twint=$(identify -format "%w\n" "${imageFile}")
    newscale=$(echo ${twint}|awk '{printf "%.5f\n", (205/$0)}')
    align="align=\"center\""
    src=$(echo "${line}"|sed 's@ @\n@g'|grep src);
    newline="<image ${align} ${src} ${twstring} scale=\"${newscale}\"/>"
    sed -i 's@'"${line}"'@'"${newline}"'@' kozem.xml
  fi
done
