#!/bin/bash

set -euo pipefail

AGE_IN_DAYS=${AGE_IN_DAYS:-183}
# convert to format we need for comparison below
newest_date=$(date --date="${AGE_IN_DAYS} days ago" +%Y%m%d)

# the pattern is from https://github.com/linux-system-roles/test-harness/blob/master/test/run-tests#L1107
# results_dir = f"{task.owner}-{task.repo}-{task.id_}-{timestamp}"
# where task.id_ is from https://github.com/linux-system-roles/test-harness/blob/master/test/run-tests#L376
# self.id_ = f"pull-{owner}_{repo}-{pull}-{self.head[:7]}-" + image["name"]
# we want to delete files older than AGE_IN_DAYS days, except that we do not want to delete
# the newest one from ROLE IMAGENAME
# for example
# ./linux-system-roles-nbde_client-pull-linux-system-roles_nbde_client-49-f70235e-rhel-8-20211011-190828
# or
# ./lsr-citool_ci-testing-19-4c9daf6_20211109-140712
find -maxdepth 1 -type d | while read dir; do
    # match 1 is rolename - match 2 is image (name-ver) - match 3 is date
    # if [[ "$dir" =~ ^./linux-system-roles-[[:alnum:]_-]+-pull-linux-system-roles_([[:alnum:]_-]+)-[[:digit:]]+-[[:alnum:]]+-([[:alnum:]]+-[[:digit:]]+)-([[:digit:]]+)-[[:digit:]]+$ ]]; then
    #     echo "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}" "$dir"
    # fi
    if [[ "$dir" =~ ^./lsr-citool_([[:alnum:]_-]+)-[[:digit:]]+-[[:alnum:]]+_([[:digit:]]+)-[[:digit:]]+$ ]]; then
        echo "${BASH_REMATCH[1]}" "unknown" "${BASH_REMATCH[2]}" "$dir"
    fi
done | sort -n -r | while read role image date dir; do
    latest_file=".latest_${role}_${image}"
    if [ -f "$latest_file" ]; then
        # we have already see the latest log for $role $image
        # all others are candidates for deletion
        if [ "$date" -lt "$newest_date" ]; then
            rm -rf "$dir"
        fi
    else
        echo keeping $role $image $date $dir
        echo "$dir" > "$latest_file"
    fi
done
rm -rf .latest_*
