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

days=${1:-15}

export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:$PATH

function get_appids_to_idle() {
    /usr/sbin/oo-list-stale $days 2>/dev/null | /bin/awk '{print $1}'
}

function print_stats() {
    (
        echo -n "$1: " ;
        /usr/sbin/oo-idler-stats
    ) | /usr/bin/logger -p local0.notice -t oo-autoidler
}

(
    if ! flock -e -n 9
    then
      /usr/bin/logger -p local0.warn -t oo-autoidler "previous instance of oo-autoidler is still running"
      exit 1
    fi

    print_stats "Before"

    for user in `get_appids_to_idle`
    do
        /usr/sbin/oo-idler -n -u $user > /dev/null 2>&1
    done

    print_stats "After"
) 9> /var/lock/oo-autoidler
exit 0