#!/bin/env oo-ruby
#--
# Copyright 2010 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#++

# Script to detect which gears have been accessed
# within the specified number of days

require 'rubygems'
require 'json'
require 'open4'
require 'tempfile'

days = if ARGV[0].nil?; 1 else ARGV[0].to_i; end

IO.foreach("/etc/openshift/node.conf") { |line|
    next if line =~ /^#/
    next if line =~ /^$/
    if line.include?"#"
        name,value = line.split("#")[0].split("=")
    else
        name,value = line.strip.split[0].split("=")
    end
    next if name.nil? or value.nil?
    ENV[name]=value.gsub('"','').strip
}

gears = []
status = Open4.popen4 "find #{ENV["LAST_ACCESS_DIR"]} -mindepth 1 -mtime -#{days}" do |pid, stdin, stdout, stderr|
  stdin.close

  stdout.each { |k|
    k.chomp!
    accessed = File.read(k).chomp # %d/%b/%Y:%H:%M:%S %z
    gears << { :uuid => File.basename(k), :access_time => accessed }
  }
end
exit 1 unless 0 == status.exitstatus

payload = { :nurture_action => "update_last_access", :gear_timestamps => gears}

scratch = Tempfile.new("list_access")
begin
  scratch.write("#{payload.to_json}")
  scratch.rewind
  sleep(rand(600) + 1)
  cmd = "curl  -k -X POST -H \"Content-Type:application/json\" -d @#{scratch.path} https://#{ENV['BROKER_HOST']}/broker/nurture"
  pid, stdin, stdout, stderr = Open4.popen4(cmd)
  Process::waitpid2 pid
ensure
  scratch.close
  scratch.unlink
end
