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

kwctl="${KWCTL_CMD:-kwctl}"
policies="kubewarden-policies.tar.gz"
list="kubewarden-policies.txt"

usage () {
    echo "USAGE: $0 [--policies-list kubewarden-policies.txt] [--policies kubewarden-policies.tar.gz]"
    echo "  [-l|--policies-list path] text file with list of policies; one police per line."
    echo "  [-p|--policies path] tar.gz generated by kwctl save."
    echo "  [-h|--help] Usage message"
}

while [[ $# -gt 0 ]]; do
    key="$1"
    shift
    case $key in
        -p|--policies)
        policies="$1"
        shift # past value
        ;;
        -l|--policies-list)
        list="$1"
        shift # past value
        ;;
        -h|--help)
        help="true"
        ;;
        *)
        usage
        exit 1
        ;;
    esac
done

if [[ -v help ]]; then
    usage
    exit 0
fi

pulled=()
while IFS= read -r i; do
    [ -z "${i}" ] && continue
    if $kwctl pull "${i}" > /dev/null 2>&1; then
        echo "Policy pull success: ${i}"
        pulled+=("${i}")
    else
        echo "Policy pull failed: ${i}"
    fi
done < "${list}"

echo "Creating ${policies} with ${#pulled[@]} policies"
$kwctl save "${pulled[@]}" --output "${policies}"

