#!/bin/bash

# Strict mode
set -euo pipefail
IFS=$'\n\t'

BASENAME=$(basename $0)

# Define role subdirectories
VALID_SUBDIRS=(defaults files handlers meta tasks templates vars)
DEFAULT_SUBDIRS=(defaults tasks)

function usage {
    cat << END_OF_HELPTEXT
Usage: $BASENAME ROLENAME [SUBDIRS]...

Creates a skeleton for an Ansible role under ./roles/ROLENAME with
subdirectories and main.yml files.

SUBDIRS is a subset of the following sub directories:
  ${VALID_SUBDIRS[@]}

If SUBDIRS is not specified, it defaults to:
  ${DEFAULT_SUBDIRS[@]}
END_OF_HELPTEXT
}

function inarray {
    local match="$1"; shift
    local el
    for el; do
        [[ "$el" == "$match" ]] && return 0
    done
    return 1
}

# Show help if no arguments are given or one of them is --help
[[ $# -eq 0 ]] && usage && exit 0

for arg in $@; do
    [[ $arg == "--help" ]] && usage && exit 0
done

# Parse arguments
ROLENAME=$1

if [[ $# -eq 2 && $2 == all ]]; then
    # Special value all: create all subdirectories
    SUBDIRS=("${VALID_SUBDIRS[@]}")
elif [[ $# -gt 1 ]]; then
    SUBDIRS=()

    for arg in "${@:2}"; do
        if ! inarray $arg "${VALID_SUBDIRS[@]}"; then
            echo "Unknown role subdirectory: $arg" >&2
            exit 1
        fi
        SUBDIRS+=($arg)
    done
else
    SUBDIRS=("${DEFAULT_SUBDIRS[@]}")
fi

ROLEDIR="roles/$ROLENAME"

# Create base directory for role
mkdir -p "$ROLEDIR"

# Create skeleton
for subdir in "${SUBDIRS[@]}"; do
    echo "Creating $ROLEDIR/$subdir"
    mkdir -p "$ROLEDIR/$subdir"

    case "$subdir" in
        defaults|handlers|meta|tasks|vars)
            filename="$ROLEDIR/$subdir/main.yml"
            echo "Creating $filename"
            touch "$filename"
        ;;
    esac
done
