#!/usr/bin/env /Applications/Server.app/Contents/ServerRoot/usr/bin/ruby

##
# Copyright (c) 2009-2014 Apple Inc. All Rights Reserved.
#
# IMPORTANT NOTE: This file is licensed only for use on Apple-branded
# computers and is subject to the terms and conditions of the Apple Software
# License Agreement accompanying the package this file is a part of.
# You may not port this file to another platform without Apple's written consent.
#
# IMPORTANT NOTE: This file is licensed only for use with the Wiki Server feature
# of the Apple Software and is subject to the terms and conditions of the Apple
# Software License Agreement accompanying the package this file is part of.
##

require 'rubygems'
require 'date'
require 'yaml'

$LOAD_PATH << File.join(File.expand_path(File.dirname(__FILE__)), 'lib')

require 'collaboration'

svc = Collaboration::ServiceClient.new

ssn = responseData = svc.execute('AuthService', 'currentOrNewSession')
svc.session_guid = ssn.guid

if Process.uid == 0
  svc.execute('AuthService', 'sudoToBestGuessForUserWithLogin:', ENV['SUDO_USER'] || ENV['USER'])
end

e = svc.execute('ContentService', 'entityForGUID:', ARGV[0])

if e.kind_of?(Collaboration::EntityPlaceholder)
    puts e.reason
    exit 1
end

tmpfilepath = '/tmp/entity-'+e.guid
File.open(tmpfilepath, 'w') do |f|
    f.write(YAML::dump(e))
end

before_sum = `md5 -q #{tmpfilepath}`

editor=ENV['EDITOR'] || '/usr/bin/vim'
system(editor, tmpfilepath)

after_sum = `md5 -q #{tmpfilepath}`

if before_sum == after_sum
    puts 'no changes'
else
    e = YAML::load(File.open(tmpfilepath))

    system('/bin/rm', tmpfilepath)

    cs = Collaboration::EntityChangeSet.new
    cs.entityGUID = e.guid
    cs.changes = e.xml_properties.map{|p| [ p.to_s, e.send(p) ] }
    cs.changeType = 'edit'
    cs.changeAction = 'UPDATE'
    cs.entityRevision = e.revision
    cs.changeComment = 'vientity by ' + ENV['USER']
    svc.execute('ContentService', 'updateEntity:', cs)
end
