#!/bin/bash

# check if sectool is available
command -v sectool >/dev/null 2>&1 || { echo >&2 "sectool is not installed.  Aborting."; exit 1; }

# check if ansible is available
command -v ansible >/dev/null 2>&1 || { echo >&2 "ansible is not installed.  Aborting."; exit 1; }

# check if ansible-playbook is available
command -v ansible-playbook >/dev/null 2>&1 || { echo >&2 "ansible-playbook is not installed.  Aborting."; exit 1; }

function help {
    echo "Usage: $0 -d <playbook>"
    echo "Options:"
    echo "  -d, --dry-run: Run ansible-playbook in dry run mode (don't apply changes)"
    exit 1
}

if [ -z $ANSIBLE_USER ]; then
    echo "ANSIBLE_USER environment variable not set"
    exit 1
fi

# parse arguments
while [ "$1" != "" ]; do
    case $1 in
        -d | --dry-run )        shift
                                DRY_RUN="-DC"
                                ;;
        -h | --help )           help
                                ;;
        * )                     PLAYBOOK=$1
                                break
                                ;;
    esac
done

if [ -z "$PLAYBOOK" ]; then
    echo "Playbook not specified"
    help
else
    if [ ! -f "$PLAYBOOK" ]; then
        echo "Playbook $PLAYBOOK not found"
        help
    fi
fi

if [ -z "$DRY_RUN" ]; then
    echo "Applying playbook $PLAYBOOK"
else
    echo "Dry run playbook $PLAYBOOK"
fi

# execute ansible-playbook
sectool exec ansible-playbook -u $ANSIBLE_USER $DRY_RUN $PLAYBOOK
