#!/usr/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 whether the app has not been accessed
# for the specified number of days
#
# exit status
# when 0: gear has not been access in $1 days
#         -OR- gear has never been accessed
# when 1: exception occurred
# when 5: gear has been active within $1 days

require 'date'

if ARGV[0].nil? or ARGV[1].nil?
  $stderr.write("Usage: #{$0} [UUID] [DAYS]\n")
  exit(1)
end

OPENSHIFT_GEAR_UUID = ARGV[0]
IDLE_FOR = ARGV[1].to_i * 24
LAST_ACCESS_DIR = '/var/lib/openshift/.last_access'

file_path = File.join(LAST_ACCESS_DIR, OPENSHIFT_GEAR_UUID)
if File.exists?(file_path)
  File.open(file_path, 'r') do |file|
    last_access_time = file.read
    d1 = DateTime.strptime(last_access_time, "%d/%b/%Y:%H:%M:%S %Z")
    d2 = DateTime.now
    hours = ((d2 - d1) * 24).to_i
    if hours >= IDLE_FOR
      exit 0
    else
      # We return 5 since 1 is returned on exceptions
      exit 5
    end
  end
else
  # If application has yet to be accessed, it's "idle"
  exit 0
end
