#!/usr/bin/env sh

#
# phl-org: manage a phlog with org-mode
#
# KatolaZ <katolaz@freaknet.org> (2018)
#

INFILE=${1:-/dev/stdin}
DESTDIR=${2:-"."}
pad="    "
FILTER="par 68ftp4"
headpad="+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"

## if you are under *BSD, you'd probably use SED=gsed
##
#SED=gsed

SED=sed

## function
write_gophermap(){

    buff=$1
    curdir=$2
    curfile=$3
    INDEX=$4
    if [ ! -d "$curdir" ]; then
        mkdir "$curdir";
    fi
    echo $buff | eval "$FILTER"  > "$curfile"
    echo "1$curdir\t$curdir" >> $INDEX
}


##function
gophermap_header(){

    GOPHERMAP=$1

    cat <<EOF>$GOPHERMAP
+++++++++++++++++++++++++++++
+   This is my gopherhole   +
+++++++++++++++++++++++++++++


EOF
    
}



## function
org2phlog(){

    FILEIN=$1
    INDEX=$2
    curfile=""
    buff=""
    IFS="
"
    while read line; do
        
        #echo $wholeline | ${SED} -r -e '/^\* /p'
        if [ -n "$(echo $line | ${SED} -r -n -e '/^\* /p')" ]; then
            if [ -n "$curfile" ]; then
                write_gophermap $buff $curfile "$curfile/gophermap" $INDEX
            fi
            buff="$headpad\n\n$pad$line\n\n$headpad"
            curfile=$(echo $line | ${SED} -r -e 's/^\* //g' -e 's/\ /_/g;s/\t/_/g;s/</-/g;s/>/-/g;s/://g')
            if [ -z "$curfile" ]; then
               curfile="(blank)"
            fi
            curfile="$curfile"
        else
            buff="${buff}\n    $line"
        fi
    done<$FILEIN
    if [ -n "$curfile" ]; then
        write_gophermap $buff $curfile "$curfile/gophermap" $INDEX
    fi
}

#echo "INFILE: $INFILE"

gophermap_header ./gophermap
org2phlog $INFILE ./gophermap