#!/bin/bash
#
# Script to unblock proposals stuck in committing stage.
#
# WARNING: usage of this script is unsupported, unless you have been
# specifically told to run it as part of a support request!
#
# This should *only* be run in special circumstances, i.e. as a
# workaround for proposals getting stuck, which is a bug arising from
# a fundamental weakness in the design of Crowbar 1.x.  For more
# details, see this bug (SUSE internal only):
#
#   https://bugzilla.novell.com/show_bug.cgi?id=840255
#
# Example usage:
#
#   reset_proposal dns
#   reset_nodes

ME="`basename $0`"

main () {
    if [ "$1" == '-h' ] || [ "$1" == '--help' ]; then
        usage 0
    fi
    # or use getoptsx
}


reset_proposal () {
    if [ $# = 0 -o $# -gt 2 ]; then
        cat >&2 <<EOF
Usage: $ME <barclamp> [<proposal name>]
Proposal name defaults to "default".
EOF
        exit 1
    fi

    bc="$1" proposal="${2:-default}"
    data_bag="bc-${bc}-${proposal}"
    editor=$( cat <<-EOF
      sed -i 's/"crowbar-committing": true/"crowbar-committing": false/'
EOF
    )
    knife data bag edit crowbar $data_bag -e "$editor"
}

# unblocking nodes stuck in applying

reset_nodes () {
    if [ $# != 0 ]; then
        cat >&2 <<EOF
Usage: $ME
EOF
        exit 1
    fi

    editor=$( cat <<-EOF
        sed -i 's/"state": "applying"/"state": "ready"/'
EOF
    )
    knife role list | grep '^ *crowbar-.*_' | while read role; do
        echo "Changing $role state to 'ready' if in 'applying' state ..."
        knife role edit $role -e "$editor"
    done
}

case "$0" in
    *reset_proposal)
        reset_proposal "$@"
        ;;
    *reset_nodes)
        reset_nodes "$@"
        ;;
    *)
        echo >&2 "BUG: $0 invoked in unknown mode"
        exit 1
        ;;
esac
