#!/usr/bin/env bash

SF_REPOSITORY=http://aros.sourceforge.net/downloads/nightly/

if [[ "$1" == "system" || "$1" == "powerpc32" ]]; then
    echo "NO_SDK"
    if [ ! -f NO_SDK ]; then
        touch NO_SDK
        touch .unpacked-NO_SDK
    fi
    exit 0
else
    TARGET="$1"
fi

if [[ "$TARGET" == "powerpc" ]]; then
    SDK_TYPE="ppc"
else
    if [[ "$TARGET" == "i386" ]]; then
        SDK_TYPE="i386"
    else
        echo "$TARGET unsupported target cpu"
        exit 1
    fi
fi

LOCAL_SDK=$(ls * | grep "AROS-.*$SDK_TYPE-all-sdk.tar.bz2")

if [ -n "$LOCAL_SDK" ]; then
    for SDK in "$LOCAL_SDK"; do
        if [ -f "$SDK" ]; then
            SDK_ARCH="$SDK"
        fi
    done
else
    SDKS=$(curl -s -l "$SF_REPOSITORY" | grep folder\.gif | awk -F/ '{print $4}' | awk -F">" '{print $2}')

    for SDK_DATE in $SDKS; do
        TMP_SDK_ARCH="AROS-$SDK_DATE-$SDK_TYPE-all-sdk.tar.bz2"
        SDK_GIF="unknown\.gif"
        SDK_DIR="$SF_REPOSITORY$SDK_DATE/Development_Tools/"
        SDK=$(curl -s -l "$SDK_DIR")
        if echo "$SDK" | grep -q "$SDK_GIF.*$TMP_SDK_ARCH"; then
            SDK_ARCH="$TMP_SDK_ARCH"
            SDK_URL="$SDK_DIR""$SDK_ARCH"
        fi
    done

    if wget -t 5 -T 5 -c "$SDK_URL" -O sdk.tmp; then
        mv sdk.tmp "$SDK_ARCH"
    fi
fi

echo "$SDK_ARCH"
