g2e/g2e.awk

105 lines
2.4 KiB
Awk

# awk -f g2e.awk example-gpub/
BEGIN{
gpubdir = ARGV[1]
tdir = "templates/" # templates dir
epubtdir = "template-epub/"
epubodir = "out/"
metadatafile = gpubdir "metadata.txt"
# read metadata file fields
while( getline < metadatafile ){
key = $1
sub(":","",key)
value = $2
for(i=3;i<=NF;i++) value = value " " $i
meta[key] = value
# set index file as an argument to be read
if(key == "index" ){
ARGV[1] = (gpubdir value) # overwrite argument 1
# store index dirname:
indexdirname = value
sub(/[^/]+\.gmi$/,"",indexdirname)
}
}
# read linked files from index and append as arguments to process
while( getline < (gpubdir meta["index"]) ){
if($1~"=>") ARGV[ARGC++] = gpubdir indexdirname $2
}
# setup epub
system( "mkdir -p " epubodir "OEBPS" )
system( "mkdir -p " epubodir "META-INF" )
system( "cp -u " tdir "container.xml " epubodir "META-INF/" )
system( "cp -u " tdir "mimetype " epubodir )
# read templates
templatefiles ="find " tdir " -type f -not -name '.*'"
while( (templatefiles | getline )>0 ){
tpath = $0
tkey = tpath
sub(tdir, "", tkey)
RS = "\f" # to get the whole file in one getline
getline templates[tkey] < tpath
RS = "\n"
}
content = write_template( "content-header.opf", meta )
toc = write_template( "toc-header.ncx", meta )
spinetoc = " <spine toc=\"ncx\">\n"
}
# write the template into output, replacing {keys} with contents of values["keys"]
function write_template( templatek, values ){
output = ""
line = templates[templatek]
while(match(line,/\{[^{}]+\}/)){ # has {key}
key = substr(line,RSTART+1,RLENGTH-2)
output = output substr(line, 1, RSTART-1) # before {key}
output = output values[key]
line = substr(line, RSTART+RLENGTH)
}
output = output line "\n"
return output
}
# index file links
ARGIND==1 && /^=>/{
id = $2
sub(/.gmi$/,"",id)
name = $3
for(i=4;i<=NF;i++) name = name " " $i
ch["id"] = id
ch["name"] = name
ch["num"]++
content = content " <item id=\"" id "\" href=\"" id ".xhtml\" media-type=\"application/xhtml+xml\"/>\n"
spinetoc = spinetoc " <itemref idref=\"" id "\" />\n"
toc = toc write_template( "toc-navmap.ncx", ch )
}
# when finished reading the index:
ARGIND==2 && FNR==1{
content = content " </manifest>\n\n" spinetoc " </spine>\n\n</package>"
printf content > epubodir "OEBPS/content.opf"
toc = toc "</ncx>"
printf toc > epubodir "OEBPS/toc.ncx"
}
# content files
ARGIND>1{
# print $0
}
END{
}