#!/bin/bash

wikiname=$1
FOSSILBIN=fossil

if [ x"$wikiname" == "x" ];then
  echo "Usage: viwiki wikipagename"
  exit
fi

$FOSSILBIN sync

wikitmpfile=`mktemp /tmp/${USER}_wikiedit.XXXXXXX`
if ! $FOSSILBIN wiki export "$wikiname" 2> /dev/null  1> $wikitmpfile ;then
    cat /dev/null > $wikitmpfile
    wikipagestate='new'
else
    wikipagestate='existing'
fi

if [ x"$EDITOR" == "x" ];then
	EDITOR="gvim -f"
fi

echo $EDITOR | grep -q -e gvim
isGvim=$?

echo $EDITOR | grep -q -e 'gvim.*-f'
hasF=$?

if [[ $isGvim == 0 && $hasF != 0 ]]; then
	EDITOR="$EDITOR -f"
fi

$EDITOR $wikitmpfile

if [ $wikipagestate == 'new' ];then
  $FOSSILBIN wiki create "$wikiname" $wikitmpfile
else
  $FOSSILBIN wiki commit "$wikiname" $wikitmpfile
fi

$FOSSILBIN sync

rm -f $wikitmpfile
