#!/bin/bash
#--
# 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.
#++

source /etc/openshift/node.conf
GEAR_GECOS=${GEAR_GECOS:-"OpenShift guest"}

days=${1:-15}

function gear_dirs() {
    grep ":${GEAR_GECOS}:" /etc/passwd | cut -d: -f6
}

for APPHOME in $(gear_dirs); do
    [ ! -d "$APPHOME" ] && continue

    # Is stale detection disabled
    [ -e "$APPHOME/.disable_stale" ] && continue

    # Only list gears that have any Frontend Mappings defined
    if grep -r "Mappings:" `find $APPHOME -name 'manifest.yml'` &> /dev/null ; then
        # Determine if something was committed using the git objects directory
        objects_modified=$(find "$APPHOME/git" -mindepth 2 -maxdepth 2 -name objects -mtime -$days)
        if [ -z "${objects_modified}" ]; then
            uuid=$(basename "$APPHOME")
            if /usr/sbin/oo-app-idle "$uuid" $days; then
                echo "$uuid is stale"
            fi
        fi
    fi
done

