#!/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 kubewarden-policies.tar.gz] --registry my.registry.com:5000"
    echo "  [-l|--policies-list path] text file with list of policies; one image per line."
    echo "  [-p|--policies path] tar.gz generated by kwctl save."
    echo "  [-r|--registry registry:port] target private registry:port."
    echo "  [-s|--sources-path path] kwctl sources path."
    echo "  [-h|--help] Usage message"
}

pushPolicy() {
    newPolicyUrl=$1
    if [[ -n $sourcesPath ]]; then
        $kwctl push "$policy" "$newPolicyUrl" --sources-path "$sourcesPath"
    else
        $kwctl push "$policy" "$newPolicyUrl"
    fi
}

while [[ $# -gt 0 ]]; do
    key="$1"
    shift
    case $key in
        -r|--registry)
        registry="$1"
        shift # past value
        ;;
        -l|--policies-list)
        list="$1"
        shift # past value
        ;;
        -p|--policies)
        policies="$1"
        shift # past value
        ;;
        -s|--sources-path)
        sourcesPath="$1"
        shift # past value
        ;;
        -h|--help)
        help="true"
        ;;
        *)
        usage
        exit 1
        ;;
    esac
done
if [[ -v help ]]; then
    usage
    exit 0
fi
if [[ -z ${registry:-} ]]; then
    usage
    exit 1
fi

$kwctl load --input "${policies}"

policies=()
while read -r policy; do
    policies+=("${policy}");
done < "${list}"

for policy in "${policies[@]}"; do
    if [[ $policy == registry://* ]]; then
       # replace registry with the one provided as parameter.
       # e.g. registry://ghcr.io/kubewarden/policies/capabilities-psp:v0.1.9 -> registry://localhost:5000/kubewarden/policies/capabilities-psp:v0.1.9
       oldPolicyUrl=$(awk -Fregistry:// '{print $2}' <<< "$policy")
       oldRegistry=$(echo "$oldPolicyUrl" | cut -f1 -d"/")
       newPolicyUrl="registry://${oldPolicyUrl/$oldRegistry/$registry}"
       pushPolicy "$newPolicyUrl"
    fi
    if [[ $policy == https://* ]]; then
       # replace registry with the one provided as parameter.
       # e.g. https://github.com/kubewarden/pod-privileged-policy/releases/download/v0.1.6/policy.wasm -> registry://localhost:5000/kubewarden/pod-privileged-policy/releases/download/v0.1.6/policy.wasm
       oldPolicyUrl=$(awk -Fhttps:// '{print $2}' <<< "$policy")
       newPolicyUrl="registry://$registry/${oldPolicyUrl#*/}"
       pushPolicy "$newPolicyUrl"
    fi
done
