#!/bin/bash

# Copyright (C) 2009-2010 Nokia Corporation. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


set -e
set -u

# wiki variables
importuser="wikiuser"
importcomment="importing documentation, see [[Meta:Problems in the LaTeX2HTML2Wiki import process]]"
pathToWiki='/var/lib/mediawiki'
titlePrefix="Documentation"
simc="" # simulate command, "" or echo
inpath="releases/wiki"
function help_func () 
{
    cat << end_of_help_text
     
USAGE: 
   ./maemodoc-importwiki [--in <input dir>] [--out <output location in wiki>] [--wikipath <dir>] [--help] [--simulate]

Imports a set of wiki files and images into a MediaWiki installation using MediaWiki's maintenance php scripts. Overrides any existing files with matching names.

OPTIONS
----------
--in <path>:          A folder of wiki files and images, default: "${inpath}"
--out <title prefix>  A common high-level name for the docs, default:
                      "$titlePrefix". For example, a wiki file with a main 
                      title "=Kernel=" will be imported as 
                      "http://wiki.org/$titlePrefix/Kernel".
--wikipath <dir>      Path to MediaWiki installation, default: 
                      "${pathToWiki}"
--simulate            Does not actually import, but simulates what it would do.            
--help                This help text.

Example:
---------
Importing wiki files into a MediaWiki installation:
./maemodoc-importwiki --in releases/wiki/test/ --out "$titlePrefix"
 
end_of_help_text
}

# auxiliary function for wiki_file_import: computes an import title
# for a wiki file for use with importTextFile.php --title
#   param $1: wiki file  
#   returns global var $title
function get_import_title(){  
#  local basis="${titlePrefix}"
#  local file="$1"
#                                                
#  local articletitle=`grep -m 1 -e "=$" ${file}|sed -e 's/^\(=\+\) *\(.*[^ ]\) *\1/\2/'`
#  
#  set +e # disable stop-on-error
#  
#  echo ${file}|grep -qe "index";
#  local index=$?
#  echo ${file}|grep -qe "wiki[0-9]\{1,\}";
#  local split=$?
#  echo ${file}|grep -q "wiki1";
#  local splitindex=$?
#  
#  set -e #re-enable stop-on-error
#  
#  if [ ${index} -eq 0 ]; then
#    if [ ${split} -ne 0 ];then # unsplit index file
#      title="${basis}";
#    else                       # very unlikely case: split index file
#      if [ ${splitindex} -eq 0 ];then # part 1
#        title="${basis}";
#      else                            # part > 1
#        title="${basis}/${articletitle}"
#      fi
#    fi
#  elif [ ${split} -eq 0 ];then #handle split files
#    local fpath=`dirname ${file}`
#    local wiki1=`basename ${file}|sed -e "s/\(node[0-9]*\.html\.wiki\).*/\1/"`
#    wiki1="${wiki1}1"
#    local wiki1title=`grep -m 1 -e "=$" ${fpath}/${wiki1}|sed -e 's/^\(=\+\) *\(.*[^ ]\) *\1/\2/'`
#    if  [ ${splitindex} -ne 0 ];then #split file but not the first part
#      title="${basis}/${wiki1title}/${articletitle}"
#    else #first part of a split file
#      title="${basis}/${wiki1title}"
#    fi
#  else
#    title="${basis}/${articletitle}"
#  fi
#  echo "** ${articletitle} -> ${title}"
#
#  title=${title/\/\//\/}

    title=""
    set +e
    if ! basename ${file} | grep -q '^index\.wiki' ; then    
	title=$( egrep -m 1 -o '= [^=]+ =' ${file} )
	title=${title/= /}
	title=${title/ =/}
	title="/${title}"
    fi
    set -e
    title="${titlePrefix}${title}"
    title=$( echo ${title} | sed 's/^./\u&/' )
}


# imports html=>wiki translated files to mediawiki installation
#   param $1: directory of wiki files
function wiki_file_import () {
    local dir=$1
    
    # Creates array which contains all the wiki files from input folder
    local wikiFilesArr=($( find ${dir} -maxdepth 1 -name "*.wiki*" \
	| awk 'BEGIN { ORS=" " } ; { print $1 }' ))

    if [[ ${#wikiFilesArr[*]} -eq 0 ]] ; then
	echo "No wiki files found in input folder."
	exit 1
    fi
    
    # import images
    $simc php ${pathToWiki}/maintenance/importImages.php --overwrite \
	--extensions=png,jpg \
	--user="${importuser}" \
	--comment="${importcomment}" "${dir}"
    
    for file in ${wikiFilesArr[*]} ; do
        # skip eclipseindex
	[[ "$file" == *eclipseindex.html.wiki ]] && continue

	# select only interesting files
        [[ "${file}" != *index.wiki ]] \
	    && [[ "${file}" != *node*.wiki ]] \
	    && continue

	get_import_title "$file"; # result in variable $title
	echo "${file} -> ${title}"

	tmp_file=$( mktemp )
	cp ${file} ${tmp_file}

	# TODO: resolve footnote prob!
	# remove footnotes
	sed -ri 's/\[\/footnode\.html\#[^]]+\]//g' ${tmp_file}

	# Add multipage links prev and next
	if echo ${file} | egrep -q '\.wiki[0-9]+$' ; then
	    part=$( basename ${file} | egrep -o '[0-9]+$' )
	    prevpart=$(( part - 1 ))
	    nextpart=$(( part + 1 ))
	    prevfile=$( echo ${file} | sed "s/${part}$/${prevpart}/" )
	    nextfile=$( echo ${file} | sed "s/${part}$/${nextpart}/" )
	    prevtitle=$( echo ${title} | sed "s/${part}$/${prevpart}/" )
	    nexttitle=$( echo ${title} | sed "s/${part}$/${nextpart}/" )

	    [[ ${prevpart} -eq 1 ]] && prevtitle=${prevtitle/ part 1/}
	    [[ ${nextpart} -eq 2 ]] && nexttitle="${nexttitle} part 2"
		

	    if [ -r ${prevfile} ] ; then
		echo "Adding link to ${prevtitle}"
		echo >> ${tmp_file}
		echo "[[${prevtitle}]]" >> ${tmp_file}
	    fi
	    
	    if [ -r ${nextfile} ] ; then
		echo "Adding link to ${nexttitle}"
		echo >> ${tmp_file}
		echo "[[${nexttitle}]]" >> ${tmp_file}
	    fi
	    echo >> ${tmp_file}
	fi

	# import
	$simc php ${pathToWiki}/maintenance/importTextFile.php \
	    --title "${title}" \
	    --user "${importuser}" \
	    --comment "${importcomment}" ${tmp_file};	
	
	rm ${tmp_file}

    done
    return 0
}


# ---- "main" part of the script --------------------------------

# handles command line options
if [ $# -ne 0 ] ; then
    while [ $# -gt 0 ] ; do
	case $1 in
	    --in) 
		if [[ $# -lt 2 || ! -e $2 ]]; then
		    echo "Please give an input dir."
		    exit 1
		fi
		inpath="$2"
		shift 2
		;;

	    --out) 
		if [[ $# -lt 2 ]] ; then
                    echo "Please give a wiki title prefix."
                    exit 1
                fi
                titlePrefix="$2"
                shift 2
		;;

	    --wikipath) 
		if [[ $# -lt 2 || ! -e $2 ]] ; then
                    echo "Please give the path to MediaWiki installation."
                    exit 1
                fi
                pathToWiki="$2"
                shift 2
		;; 

	    --simulate) 
		simc=echo
		shift
		;;

	    --help) 
		help_func
		shift
                exit 0
		;;

            *) 
		echo "Unknown option: $1"
                help_func
		shift
                exit 1
		;;
	esac
    done
else
    help_func
    exit 1
fi

# start the action!

if [[ ! -e ${pathToWiki}/maintenance/importTextFile.php ]] ; then
    echo "Please provide the path to local Mediawiki" \
	"installation by --wikipath <path>."
    exit 1
fi
wiki_file_import "$inpath"
