apiVersion: v1
kind: ConfigMap
metadata:
  name: talos-prune-script
  namespace: talos
  labels:
    app.kubernetes.io/name: talos-prune-script
    app.kubernetes.io/instance: talos
    app.kubernetes.io/part-of: talos
data:
  prune.sh: |
    DATE_RANGE=$(date -d @$(( $(date +%s) - $DATE_RANGE_SECONDS )) +%Y-%m-%dT%H:%M:%SZ);
    FILE_MATCH="${BUCKET}/cl01tl/etcd/cl01tl-${DATE_RANGE}.snap.age";
    ERROR=false;
    MESSAGE="";

    echo "";
    echo ">> Running S3 prune for Talos backup repository ${TARGET} ...";

    echo "";
    echo ">> Configured Date Range is $(date -u -d @${DATE_RANGE_SECONDS} +"%j days, %H hours, %M minutes")";
    echo ">> Backups prior to '$DATE_RANGE' will be removed";
    echo "";

    FILES=$(s3cmd ls --no-check-certificate "${BUCKET}/cl01tl/etcd/" | \
        awk -v file_match="$FILE_MATCH" '$4 < file_match && $4 !~ /\/$/ {print $4}')

    if [ $? -ne 0 ]; then
        echo "";
        echo ">> Detected error, will send message to ntfy";

        ERROR=true;
        MESSAGE="Error collecting files to delete from '${TARGET}'";

    elif [ -n "${FILES}" ]; then
        echo "";
        echo ">> Backups to be removed:";
        echo "";
        echo "$FILES";
        echo "";
        echo ">> Deleting ...";

        for file in $FILES; do
            s3cmd del --no-check-certificate -v "${file}";

            if [ $? -ne 0 ]; then
                echo ">> Detected error, will send message to ntfy";

                ERROR=true;
                MESSAGE="Error deleting file from '${TARGET}'";

            fi;
        done;

    else
        echo "";
        echo ">> No backups to remove";

        exit 0;

    fi;

    MAX_RETRIES=5;
    SUCCESS=false;

    echo "";
    echo ">> Sending message to ntfy using curl ...";

    echo "";
    echo ">> Verifying required commands ...";

    for i in $(seq 1 "$MAX_RETRIES"); do
        if apk update >/dev/null 2>&1; then
            echo ">> Attempt $i: Repositories are reachable";

            SUCCESS=true;

            break;

        else
            echo ">> Attempt $i: Connection failed, retrying in 5 seconds ...";

            sleep 5;

        fi;
    done;

    if [ "$SUCCESS" = false ]; then
        echo ">> ERROR: Could not connect to apk repositories after $MAX_RETRIES attempts, exiting ...";

        exit 1;

    fi

    if ! command -v curl >/dev/null 2>&1; then
        echo ">> Command curl could not be found, installing";

        apk add --no-cache -q curl;

        if [ $? -eq 0 ]; then
            echo ">> Installation successful";

        else
            echo ">> Installation failed with exit code $?";

            exit 1;

        fi;
    fi;

    echo "";
    echo ">> Sending to NTFY ...";

    if [ "$ERROR" = "true" ]; then
        HTTP_STATUS=$(curl \
            --silent \
            --write-out '%{http_code}' \
            -H "Authorization: Bearer ${NTFY_TOKEN}" \
            -H "X-Priority: 5" \
            -H "X-Tags: warning" \
            -H "X-Title: Talos Backup Prune Failed for ${TARGET}" \
            -d "$MESSAGE" \
            ${NTFY_ENDPOINT}/${NTFY_TOPIC}
        );

        echo ">> HTTP Status Code: $HTTP_STATUS";

        exit 1;

    else
        MESSAGE="Pruned $(echo "$FILES" | wc -l) files"

        HTTP_STATUS=$(curl \
            --silent \
            --write-out '%{http_code}' \
            -H "Authorization: Bearer ${NTFY_TOKEN}" \
            -H "X-Priority: 3" \
            -H "X-Tags: completed" \
            -H "X-Title: Talos Backup Prune Success for ${TARGET}" \
            -d "$MESSAGE" \
            ${NTFY_ENDPOINT}/${NTFY_TOPIC}
        );

        echo ">> HTTP Status Code: $HTTP_STATUS";

    fi;

    echo "";
    echo ">> Completed S3 prune for Talos backup repository ${TARGET}";
