#!/bin/sh

#   Copyright 2011 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.

usage()
{
cat << EOF

USAGE:
aeolus-cleanup [-d|--debug] [-h|--help] [-v|--verbose] [-s|--savedata] [-p|--profile]

OPTIONS:
   -h | --help       Show this message.
   -d | --debug      Debug logging mode.
   -v | --verbose    Verbose logging mode.
   -s | --savedata   Do not delete existing data.
   -p | --profile    Name of profile to use. A comma separated list can be used to specify multiple profiles.
EOF
}

args=`getopt -o :hdvsp: --long help,debug,verbose,savedata,profile -- "$@"`
if test $? != 0
     then
         usage
         exit 1
fi

SAVE_DATA=false
PUPPET_NODE='default'

eval set -- $args
while true ; do
        case "$1" in
                -h|--help) usage ; exit 1 ;  shift ;;
                -d|--debug) LOGLEVEL="--debug" ; shift ;;
                -v|--verbose) LOGLEVEL="--verbose" ; shift  ;;
	        -s|--savedata) SAVE_DATA=true ; shift ;;
                -p|--profile) PUPPET_NODE=$2 ; shift ; shift ;;
                --) shift ; break ;;
                *)  usage ; exit 1 ;;
        esac
done

export FACTER_AEOLUS_ENABLE_HTTPS=true
export FACTER_AEOLUS_ENABLE_SECURITY=false
export FACTER_AEOLUS_SAVE_DATA=$SAVE_DATA

HAS_FAILURES=0

NODE_ARRAY=(`echo $PUPPET_NODE | tr "," "\n"`)
for x in "${NODE_ARRAY[@]}"
do
    /usr/share/aeolus-configure/modules/aeolus/aeolus-node-check /etc/aeolus-configure/nodes/${x}_cleanup
    if [ $? != 0 ]; then
	exit 1
    fi
    
    puppet /usr/share/aeolus-configure/modules/aeolus/aeolus.pp \
       --modulepath=/usr/share/aeolus-configure/modules/ \
       --external_nodes "/bin/sh /usr/share/aeolus-configure/modules/aeolus/aeolus-node ${x}_cleanup" --node_terminus exec \
       --logdest=/var/log/aeolus-configure/aeolus-cleanup.log \
       --logdest=console \
       $LOGLEVEL \
       --detailed-exitcodes
    if [ $? != 0 -a $? != 2 ] ; then
        HAS_FAILURES=1
    fi
done

if [ $HAS_FAILURES == 1 ]; then
    exit 1
fi
