#!/bin/sh
if [ $# -eq 0 ]; then
    echo "Usage: smack-unique-snapshots.sh 4.4.0-alpha1-SNAPSHOT";
    exit 1;
fi

VERSION=$1
SMACK="https://igniterealtime.org/repo/org/igniterealtime/smack"
META="maven-metadata.xml"

TEMPD=$(mktemp -d)
cd $TEMPD
# Determine avail smack projects by recursively fetching subdirs
wget -q -r -l1 -nH --cut-dirs=4 --no-parent -e robots=off $SMACK

PROJECTS=()
VERSIONS=()
# smack projects will result in subdir
# get index.html of project with descending change date
# from the html, extract first .pom file name, which is latest version
for d in `ls` ; do
    if  [[ -d $d ]]; then
        PRO=$(wget -q "$SMACK/$d/$VERSION?C=M;O=D" -O- | grep -Po '(?<=a href=").*?(?=\.pom")' | head -n1);

        # Repair missing projects
        if [ ${#PRO} -le ${#d} ]; then
            PRO="$d MISSING"
        fi
        PROJECTS+=("$PRO")

        echo $PRO

        # Gradle dependency generation
        # Determine snapshot version string, which begins after project name
        PROJ_LEN=$((${#d} + 1))
        SNAP=${PRO:$PROJ_LEN}
        # Make project name camelcase and append version string
        VER="$(echo $d | sed -r 's/(^|-)(\w)/\U\2/g')Version = \"$SNAP\""
        # Append to array with first char lower case'd
        VERSIONS+=("${VER,}")
    fi
done
# print out block of gradle dependecy versions
printf "\n"
echo "Gradle Versions:"
for v in "${VERSIONS[@]}"; do
    echo $v
done

# clean up
rm -rf $TEMPD
