#!/usr/bin/env bash
set -euo pipefail

usage() {
    printf 'usage: processfixture {system|snapshot|policy|apply} FIXTURE [ARGS...]\n' >&2
    exit 64
}

[[ $# -ge 2 ]] || usage
command_name=$1
fixture=$2
shift 2

[[ -d "$fixture" ]] || {
    printf 'processfixture: fixture not found: %s\n' "$fixture" >&2
    exit 66
}

case "$command_name" in
    system)
        [[ $# -eq 0 ]] || usage
        exec /bin/cat -- "$fixture/system.tsv"
        ;;
    snapshot)
        [[ $# -eq 1 ]] || usage
        case "$1" in
            before|after) exec /bin/cat -- "$fixture/processes.$1.tsv" ;;
            *) usage ;;
        esac
        ;;
    policy)
        [[ $# -eq 0 ]] || usage
        exec /bin/cat -- "$fixture/policy.tsv"
        ;;
    apply)
        [[ $# -eq 5 ]] || usage
        requested_resource=$1
        requested_scope=$2
        requested_action=$3
        requested_parameter=$4
        requested_value=$5

        IFS=$'\t' read -r h_resource h_scope h_action h_parameter h_value h_extra \
            < "$fixture/policy.tsv"
        [[ "$h_resource" == resource && "$h_scope" == scope &&
           "$h_action" == action && "$h_parameter" == parameter &&
           "$h_value" == value && -z "${h_extra:-}" ]] || {
            printf 'processfixture: malformed policy header\n' >&2
            exit 65
        }
        IFS=$'\t' read -r resource scope action parameter value extra \
            < <(sed -n '2p' "$fixture/policy.tsv")
        [[ -n "${resource:-}" && -z "${extra:-}" ]] || {
            printf 'processfixture: malformed policy record\n' >&2
            exit 65
        }
        [[ "$requested_resource" == "$resource" &&
           "$requested_scope" == "$scope" &&
           "$requested_action" == "$action" &&
           "$requested_parameter" == "$parameter" &&
           "$requested_value" == "$value" ]] || {
            printf 'processfixture: action refused by fixture policy\n' >&2
            exit 77
        }

        printf 'action\tresource\tscope\tparameter\tvalue\n'
        printf '%s\t%s\t%s\t%s\t%s\n' \
            "$action" "$resource" "$scope" "$parameter" "$value"
        ;;
    *) usage ;;
esac
