# -*- coding: utf-8 mode: sh -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8

function get_version() {
    # lire le numéro de version dans le fichier $1
    awk '/var[ \t]*version/ {
match($0, /major: [0-9]*,/)
major = substr($0, RSTART + 7, RLENGTH - 8)
match($0, /minor: [0-9]*,/)
minor = substr($0, RSTART + 7, RLENGTH - 8)
match($0, /revision: [0-9]*,/)
revision = substr($0, RSTART + 10, RLENGTH - 11)
print major "." minor "." revision
exit
}' "$1"
}

function dump_header() {
    # lire et afficher le contenu avant-storeArea du tiddlywiki $1
    awk '
BEGIN { found = 0 }
/<div id="storeArea"/ { found = 1 }
! found { print }
' "$1"
}

function dump_footer() {
    # lire et afficher le contenu après-storeArea du tiddlywiki $1
    awk '
BEGIN {
    foundStoreArea = 0
    foundFooter = 0
}
/<div id="storeArea"/ { foundStoreArea = 1 }
foundStoreArea && /<\/div>.*<\/div>/ { foundFooter = 1; next }
foundStoreArea && /^[ \t]*<\/div>/ { foundFooter = 1; next }
foundFooter { print }
' "$1"
}

function dump_storeArea() {
    # lire et afficher le storeArea dans le tiddlywiki $1
    awk '
BEGIN { found = 0 }
/<div id="storeArea"/ { found = 1 }
found { print }
found && /<\/div>.*<\/div>/ { found = 0; next }
found && /^[ \t]*<\/div>/ { found = 0; next }
' "$1"
}

function dump_defaultStoreArea() {
    # Générer un storeArea par défaut pour le projet dont le répertoire est $1
    local today="$(date +%Y%m%d%H%M)"
    local projdir="${1:-.}"
    local title subtitle
    if [ -f "$projdir/build.properties" ]; then
        local project_name project_desc
        file_get_properties "$projdir/build.properties" project_name "" project_desc ""
        title="$project_name"
        subtitle="$project_desc"
    fi
    [ -z "$title" ] && title="$(basename "$(abspath "$projdir")")"
    [ -z "$subtitle" ] && subtitle="Gestion des t&acirc;ches"

    echo '<div id="storeArea">
<div tiddler="SiteTitle" modified="'"$today"'" modifier="JephteCLAIN" tags="systemTiddlers">'"$title"'</div>
<div tiddler="SiteSubtitle" modified="'"$today"'" modifier="JephteCLAIN" tags="systemTiddlers">'"$subtitle"'</div>
</div>'
}

function replace_storeArea() {
    # dans le tiddlywiki $1, remplacer le storeArea par le fichier $2 (par défaut, lu sur stdin)
    (
        dump_header "$1"
        if [ -z "$2" -o "$2" == "-" ]; then
            cat
        else
            cat "$2"
        fi
        dump_footer "$1"
    ) >"$1.$$"
    /bin/mv "$1.$$" "$1"
}

function upgrade_TiddlyWiki() {
    # mettre à jour le tiddly wiki $1 avec $2
    (
        dump_header "$2"
        dump_storeArea "$1"
        dump_footer "$2"
    ) >"$1.$$"
    /bin/mv "$1.$$" "$1"
}
