#!/bin/sh

# CHECK PARAMETER
usage() { printf '%s\n' "Usage: fixme_termine.sh <JAHR>"; exit 2; }
[ -z $1 ] && usage
YEAR=$1

# ENFORCE DATE FORMAT
LC_TIME=en_US
export LC_TIME
SYSTEM="$(uname)"

# GET LIST OF PUBLIC HOLIDAYS IN "YYYY-MM-DD" FORMAT.
LIST="$(curl -s "https://feiertage-api.de/api/?jahr=$YEAR" \
    | json2tsv | grep -E '^\.BW.*datum' \
    | awk -F'\t' '{ printf("%s",$3"|"); split($1,a,"."); printf("%s.%s\n",a[3],a[4]); }' \
    | sed 's/\.datum//g')"

find_friday() {
    local YMD="$1"
    [ "$SYSTEM" = "Linux" ] && \
        DATE=$(date -d "$YMD" +"%a %d.%m.%Y" | grep Fri)
    [ "$SYSTEM" = "OpenBSD" ] && \
        DATE=$(date -jf "%Y-%m-%d" +"%a %d.%m.%Y" "$YMD" | grep Fri)

    [ "$DATE" != "" ] && printf "1" || printf "0";
}

# LOOP AT MONTHS
for MONTH in 1 2 3 4 5 6 7 8 9 10 11 12;
do
    # THERE IS A FRIDAY IN THE FIRST 7 DAYS OF A MONTH
    DAY=1
    while [ $DAY -le 7 ];
    do
        # ADD LEADING ZEROS
        YMD=$(printf '%s-%02.0f-%02.0f' "$YEAR" "$MONTH" "$DAY")

        # IS THIS DAY A FRIDAY?
        if [ "$(find_friday $YMD)" -eq "1" ]; then

            # CHECK IF THIS FRIDAY IS A HOLIDY
            if printf "$LIST" | grep -q "$YMD"; then

                # FIND HOLIDAY REASON
                HOLIDAY="$(printf '%s' "$LIST" | grep "$YMD" | cut -d'|' -f2-)"

                # PRINT AND SUGGEST DAY+7
                printf '%02.0f.%02.0f.%s' "$DAY" "$MONTH" "$YEAR"
                printf '%s' " < $HOLIDAY, verschieben auf "
                printf '%02.0f.%02.0f.%s?\n' "$(($DAY+7))" "$MONTH" "$YEAR"
                break
            else
                # NO HOLIDAY, PRINT
                printf '%02.0f.%02.0f.%s\n' "$DAY" "$MONTH" "$YEAR"
            fi
            break
        fi
        DAY=$(($DAY+1))
    done
done
