#!/usr/bin/python
# Upload regression images to the wiki
#  if they do not exist or
#   if they have changed.

# imports
import mwclient
import client, page
import re
import os, sys
import hashlib

# Parse the command line
if len(sys.argv) < 3:
  print "Usage: " + sys.argv[0] + " Username Password"
  sys.exit()

# Connect to the wiki
site = mwclient.Site(('https','itk.org'), '/Wiki/')
site.login(sys.argv[1], sys.argv[2])

# Walk the baseline directory
baselines = []
baselineRoot = "Testing/Baseline"
for root, dirs, files in os.walk(baselineRoot):
  for f in files:
    extension = os.path.splitext(f)[1][1:]
    if extension == "png" :
      baselineFile = root + "/" + f
      baselines.append(baselineFile)
    else :
      print "Skipping " + root + "/" + f
# For each baseline see if there exists a wiki image
for baseline in baselines:
  # The wiki name is derived from the baseline name
  wikiname = re.sub("Testing","VTK_Examples",re.sub("/","_",baseline))
  image=site.Images[wikiname]
  if image.imageinfo:
    # Download the image
    wikiImage = image.download()
    
    # Compute md5's for the wiki image and the local baseline image
    h1 = hashlib.md5(wikiImage.read()).digest()

    file=open(baseline)
    h2 = hashlib.md5(file.read()).digest()

    if  h1 != h2 :
      print "Baseline " + baseline + " has changed, uploading..."
      site.upload(file, wikiname,'Baseline changed', ignore = True)
      file.close()
    else:
      print "Baseline " + baseline + " has not changed"
  else:
    print "Baseline " + baseline + " does not exist, uploading..."
    file=open(baseline)
    site.upload(file, wikiname,'New baseline added', ignore=True)
    file.close()
