#!/bin/bash
__SUMMARY__=$(cat <<"__TLDR__"
split-yaml

Split a Kubernetes YAML file into multiple files based on its name and kind.

Usage: split-yaml [-o result_dir] input.yaml

    -o result_dir   Write the results to this directory.  Default: current directory.
__TLDR__
)

export PS4='+ ${FUNCNAME:-(main)}:${LINENO}: '

Prog=${0##*/}
Progdir=$(dirname "$0")

ask_yn () {
    while read -rn1 -p "$* (y/n) "
    do
        echo >&2
        case $REPLY in
            [Yy]) return 0;;
            [Nn]) return 1;;
            *) echo >&2 "Enter y or n";;
        esac
    done
    return 2  # EOF
}

eecho () {
    echo >&2 "$@"
}

eprintf () {
    # shellcheck disable=SC2059
    printf >&2 "$@"
}

fail () {
    set +exu
    local ret=${1}
    shift
    echo "$Prog:" "$@" >&2
    exit "$ret"
}

warn () {
    local ret=${1}
    shift
    echo "$Prog:" "$@" >&2
    return "$ret"
}

usage () {
    echo >&2 "$__SUMMARY__"
    exit "$1"
}

is_true () {
    case "${1-}" in
        [yY]*|[tT]*|1|*true) return 0 ;;
        [nN]*|[fF]*|0|*false) return 1 ;;
    esac
    return 2  # unknown
}

require_program () {
    command -v "$1" &>/dev/null ||
        fail 127 "Required program '$1' not found in PATH"
}

if [[ $* == -h || $* == --help ]]; then
    usage 0
fi

Prefix=splitoutput__
ResultDir=$PWD
while getopts ':o:' opt; do
    case $opt in
        o) ResultDir=$OPTARG ;;
        *) eecho Bad option "$opt"; usage 2 ;;
    esac
done

shift $((OPTIND - 1))
OPTIND=1

set -o nounset
IFS=$'\n\t'
unset GREP_OPTIONS POSIXLY_CORRECT

InputFile=${1?Input file not provided}

require_program csplit
require_program yq

mkdir -p "$ResultDir" || fail 3 "Failed to create result dir $ResultDir"
csplit -z -f "${ResultDir}/${Prefix}" -b "%02d.yaml" "$InputFile" '/^---/' '{*}' || fail 4 "Failed to split input file"
for it in "${ResultDir}/${Prefix}"*.yaml
do
    NewName=$(yq -r '"\(.metadata.name)_\(.kind).yaml"' "$it")
    if [[ -z $NewName ]]
    then
        eecho "Error getting new name; skipping $it"
        continue
    fi
    mv -bv "$it" "${ResultDir}/${NewName}"
done



# vim:et:sw=4:sts=4:ts=8
