#!/bin/ksh

# if ( [ $# -eq 0 ] ) ; then
#   $0 -h
#   exit
# fi

function getPageName
{
  echo ${FileName} | sed -e "s/%2F/\//g"
  # PageName=$( echo ${FileName} | sed -e "s/%2F/\//g" )
}


function getFileOut
{
  gawk -v String=${PageName} \
       '{ if ( $1 == String ) print $2 }' \
       ${EquivFile}
}

function findWikinfo
{
  fg_wikinfo=false

  LinWiki=$( grep -n "Wikinfo(changed_ts)" ${DIRIN}/${FileName} | \
            gawk -F \: '{print $1}' )

  if [ X${LinWiki} != X ] ; then
    fg_wikinfo=true

    (( LinFin = $LinWiki - 2 ))

    LinNb=$( wc -l ${DIRIN}/${FileName} | \
             gawk '{print $1}' )
    (( SkipNb = (${LinNb} - ${LinFin} + 1) ))

    (( LinDeb = ($LinWiki + 2) ))

    if [ ${verbosity} -ge 2 ] ; then
      echo "${LinFin} ${LinNb} ${SkipNb} ${LinDeb}"
    fi
  fi
}


# Define stuff
# ============
DIRIN="oldwiki_dump"
DIROUT="newwiki_load"
DIRBIN="attachment"

if [ ! -d ${DIRIN} ] ; then
  mkdir ${DIRIN}
fi

if [ ! -d ${DIROUT} ] ; then
  mkdir ${DIROUT}
fi

if [ ! -d ${DIRBIN} ] ; then
  mkdir ${DIRBIN}
fi

EquivFile="EquivNoms.dat"
SedScript="Links.sed"
AttachFile="Attachment.dat"

Forge="forge.ipsl.jussieu.fr"
ProjectFrom="igcmg"
ProjectTo="igcmg_doc"
TracAdmin="trac-admin"
Realm="wiki"


# Arguments
# =========
# Default argument values
# -----------------------
fg_load=false
fg_extract=false
fg_attach=false
fg_dryrun=false
fg_quiet=false
fg_verbose=false
# Get arguments from command line
# -------------------------------
while getopts :hlxadqv Opt ; do
  case ${Opt} in
    h)
      echo "usage: $0 [-d] [-q] [-v]"
      echo "usage: $0 [-h]"
      echo ""
      echo "options :"
      echo "  -h : print this help and exit"
      echo "  -l : load files to new wiki"
      echo "  -x : dump files from old wiki"
      echo "  -a : extract attachments from wiki"
      echo "  -d : dryrun mode, nothing will be done"
      echo "  -q : quiet"
      echo "  -v : verbose"
      exit 0 ;;
    l)
      fg_load=true
      ;;
    x)
      fg_extract=true
      ;;
    a)
      fg_attach=true
      ;;
    d)
      fg_dryrun=true
      ;;
    q)
      fg_quiet=true
      ;;
    v)
      fg_verbose=true
      ;;
    :)
      echo "$0: -"${Opt}" option: missing value"
      exit 1
      ;;
    \?)
      echo "$0: -"${Opt}" option: not supported"
      exit 1
      ;;
  esac
done
shift $(($OPTIND-1))

if ( ${fg_dryrun} ) ; then
  fg_verbose=true
  fg_load=false
  fg_extract=false
  fg_attach=false
fi

verbosity=1
if ( ${fg_verbose} ) ; then
  verbosity=2
fi
if ( ${fg_quiet} ) ; then
  verbosity=0
fi


# A little cleaning
# =================
rm ${DIROUT}/*
rm ${AttachFile}
if ( ${fg_attach} ) ; then
  rm ${DIRBIN}/*
fi


# Construct sed script to replace links
# =====================================
gawk ' { print "s%wiki:" $1 "%wiki:" $2 "%\n" \
               "s%igcmg/wiki/" $1 "%igcmg_doc/wiki/" $2 "%\n" \
               "s%" $1 "%" $2 "%" } ' \
     ${EquivFile} >  ${SedScript}
echo "s%igcmg/attachment/wiki%igcmg_doc/attachment/wiki%" \
                  >> ${SedScript}


# Dump pages from igcmg
# =====================
if ( ${fg_extract} ) ; then
  rm ${DIRIN}/*

  Command="wiki dump"

  ssh ${ProjectFrom}@${Forge} \
      "${TracAdmin} trac/ ${Command} ${DIRIN}"
  scp -r ${ProjectFrom}@${Forge}:${DIRIN} ./
  ssh ${ProjectFrom}@${Forge} \
      "rm -r ${DIRIN}"
fi


# Construct page list
# ===================
set -A FileList $( cat FileList_Doc.txt \
                       FileList_Train.txt \
                       FileList_Util.txt )
# FileList="platform%2Ftodolist"
# FileList="platform%2Fen%2Fdocumentation%2FG_suivi"

# Process file list
# =================
for FileName in ${FileList[*]} ; do

  if [ ${verbosity} -ge 1 ] ; then
    echo "=========================================================="
  fi

  # Construct page name
  # -------------------
  PageName=$( getPageName )

  # Find output file name
  # ---------------------
  FileOut=$( getFileOut )

  if [ X${FileOut} != X ] ; then
    if [ ${verbosity} -ge 2 ] ; then
      printf "%-70.70s  %-60.60s  %-35.35s \n" \
             "${FileName}" "${PageName}" "${FileOut}"
    fi
  else
    echo "No output name for ${FileName}"
    continue
  fi


  # Look for Wikinfo macro
  # ----------------------
  findWikinfo


  # Rename file and remove wikinfo macro
  # ------------------------------------
  if ( $fg_wikinfo ) ; then
    if [ ${verbosity} -ge 1 ] ; then
      echo "head -n -$SkipNb ${DIRIN}/${FileName} \
                 > ${DIROUT}/${FileOut}"
      echo "tail -n +$LinDeb ${DIRIN}/${FileName} \
                 >> ${DIROUT}/${FileOut}"
    fi
    # if ( ! ${fg_dryrun} ) ; then
      head -n -$SkipNb ${DIRIN}/${FileName} > ${DIROUT}/${FileOut}
      tail -n +$LinDeb ${DIRIN}/${FileName} >> ${DIROUT}/${FileOut}
    # fi
  else
    if [ ${verbosity} -ge 1 ] ; then
      echo "cp ${DIRIN}/${FileName} ${DIROUT}/${FileOut}"
    fi
    # if ( ! ${fg_dryrun} ) ; then
      cp ${DIRIN}/${FileName} ${DIROUT}/${FileOut}
    # fi
  fi


  # Rename links with previously built sed script
  # ---------------------------------------------
  ls ${DIROUT}/
  sed -f $SedScript ${DIROUT}/${FileOut} > ${DIROUT}/${FileOut}.tmp

  if [ ${verbosity} -ge 2 ] ; then
    diff ${DIROUT}/${FileOut} ${DIROUT}/${FileOut}.tmp > /dev/null
    rc=$?
    if [ $rc -ne 0 ] ; then
      gvim -d ${DIROUT}/${FileOut} ${DIROUT}/${FileOut}.tmp
    fi
  fi
  if ( ! ${fg_dryrun} ) ; then
    if [ ${verbosity} -ge 1 ] ; then
      echo "mv ${DIROUT}/${FileOut}.tmp ${DIROUT}/${FileOut}"
    fi
    mv ${DIROUT}/${FileOut}.tmp ${DIROUT}/${FileOut}
  fi


  # Copy page to new wiki
  # ---------------------
  if ( ${fg_load} ) ; then
    Command="wiki load"
    scp ${DIROUT}/${FileOut} ${ProjectTo}@${Forge}:
    ssh ${ProjectTo}@${Forge} \
        "${TracAdmin} trac/ ${Command} ${FileOut}"
    ssh ${ProjectTo}@${Forge} "rm -v ${FileOut}"
  fi


  # Process attachments
  # -------------------
  if ( ${fg_attach} ) ; then
    
    # Find attachments on old wiki
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Command="attachment list"
    set -A AttachList $( ssh ${ProjectFrom}@${Forge} \
        "${TracAdmin} trac/ ${Command} ${Realm}:${PageName}" | \
        tail -n +4 | gawk '{ print $1 }' )

    for AttachName in ${AttachList[*]} ; do
      echo ${AttachName}

      # Extract attachments from old wiki
      # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      Command="attachment export"
      ssh ${ProjectFrom}@${Forge} \
          "${TracAdmin} trac/ ${Command} ${Realm}:${PageName} \
           ${AttachName} ${AttachName}"
      scp ${ProjectFrom}@${Forge}:${AttachName} $DIRBIN/

      # Load attachments on new wiki
      # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      if ( ${fg_load} ) ; then
        Command="attachment add"
        scp $DIRBIN/${AttachName} ${ProjectTo}@${Forge}:
        ssh ${ProjectTo}@${Forge} \
            "${TracAdmin} trac/ ${Command} ${Realm}:${FileOut} \
             ${AttachName}"
        ssh ${ProjectTo}@${Forge} "rm ${AttachName}"
      fi
      ssh ${ProjectFrom}@${Forge} "rm ${AttachName}"
    done
  fi

done

exit