#!/bin/sh
# title: edit wiki page
# description: checkout/checkin doc page from fossil repo, edit via $EDITOR
# version: 0.2
#
# Edits or creates new wiki page using local editor.
#
PAGE="$1"
FILE=""
ADDFN=""
EXISTS=0

# pagename
if [ -z "$PAGE" ]
then
  echo Syntax: $0 PageName
  exit
elif [ "$PAGE" = "ls" ]
then
  fossil wiki ls
  exit
fi

# test
EXISTS=$(fossil wiki ls | egrep "^$PAGE$")
if [ ! $EXISTS ]
then
  PAGE=$(fossil wiki ls|egrep -m1 -i "^$PAGE$" || fossil wiki ls|grep -m1 -i "$PAGE")
  if [ -n "$PAGE" ]
  then
    echo "Found similar page name: '$PAGE'"
    EXISTS=1
  else
    PAGE=$1
    echo "New page: '$PAGE'"
    ADDFN=".new"
  fi
fi

# export
FILE="/tmp/fossilwikiedit$ADDFN.$PAGE"
fossil sync
fossil wiki export "$PAGE" "$FILE"

# edit
MD5=$(md5sum "$FILE")
$EDITOR "$FILE"
MD5NEW=$(md5sum "$FILE")

# save?
if [ "$MD5NEW" != "$MD5" ]
then
  if [ $EXISTS ]
  then
    fossil wiki commit "$PAGE" "$FILE"
  else
    fossil wiki create "$PAGE" "$FILE" --mimetype text/x-markdown
  fi
  if [ $? ]
  then
    fossil sync
    rm "$FILE"
  fi
else
  rm "$FILE"
fi
