#! /bin/sh

. ./gmi

root="$(pwd)"

source_files="$(find "$1" | sort | sed "s/^$1\///g" | tail -n +2 | sed '/.*\.draft/d')"
dest_files="$(find "$2" 2> /dev/null | sort | sed "s/^$2\///g" | tail -n +2)"

for dest_file in $dest_files; do
    echo "$source_files" | grep -q "$dest_file" || rm -rf "$2/$dest_file"
done

for source_file in $source_files; do
    cd "$root/$1"
    [ "$(file "$source_file" | awk '{ print $NF }')" = "directory" ] && continue
    
    eval $(stat -s "$root/$2/$source_file" 2> /dev/null || echo st_mtime=0)
    dest_mtime=$st_mtime
    eval $(stat -s "$source_file")
    source_mtime=$st_mtime

    if [ "$(echo "$source_file" | rev | cut -d'.' -f1 | rev)" != "gmi" ]; then
        cp "$source_file" "$root/$2/$source_file"
        continue
    fi

    if [ ! $dest_mtime -gt $source_mtime ] || cat "$source_file" | grep -Eq '[^\\]\$\(LINK'; then
        echo "Converting $source_file..."
        CURDIR="$(dirname "$source_file")"
        CURFILE="$(basename "$source_file")"
        cd "$CURDIR"
        mkdir -p "$root/$2/$CURDIR"
        . "$root/pre" < "$CURFILE" > "$root/$2/$source_file"
    fi
done