#!/bin/bash

SOURCE_MIRROR_URL="http://software-dl.ti.com/processor-sdk-mirror/sources"
NONINTERACTIVE=false
DL_DIR="$PWD"

usage() {
    cat << __EOF__

Usage: $0 [options] <src_pkg_list1> [<src_pkg_list2> ...]

options:

    -h : Display help and usage (this message)
    -m : Mirror URL (default: "${SOURCE_MIRROR_URL}")
    -o : Downloads directory (default: "${DL_DIR}")
    -y : Download without interaction

__EOF__
}

[ $# -gt 0 ] || { usage; exit 1; }

src_pkg_lists=()
while [ $# -gt 0 ]
do
    case "$1" in 
        -h|--help) usage; exit 0;;
        -m) SOURCE_MIRROR_URL="$2"; shift;;
        -o) DL_DIR="$2"; shift;;
        -y) NONINTERACTIVE=true;;
        -*) echo "Unrecognized option!"; usage; exit 1;;
        *)  src_pkg_lists=("${src_pkg_lists[@]}" "$1");;
    esac
    shift
done

if [ ${#src_pkg_lists[@]} -eq 0 ]
then
    echo
    echo "Error: Please provide one of more source package lists."
    usage
    exit 1
fi

[ -d "${DL_DIR}" ] || mkdir -p "${DL_DIR}"

total_size=0
while read file
do
    [ ! -e "${DL_DIR}/${file}.done" ] || continue
    file_size=0
    file_size=$(wget --spider "${SOURCE_MIRROR_URL}/${file}" 2>&1 | sed -ne 's|^Length: \([0-9]*\) .*|\1|p')
    total_size=$[total_size+file_size]
    echo "Size = $file_size/$total_size : $file"
done < <(cat "${src_pkg_lists[@]}" | sort -u)

echo
echo "Total Download Size: $[total_size/1024/1024] MB"
echo

if ! ${NONINTERACTIVE}
then
    opt=""
    while [ -z "$opt" ]
    do
        read -p "Would you like to continue? [y/n] " opt
        case "$opt" in
            y) :;;
            n) exit 0;;
            *) echo; echo "Choice \"$opt\" not recognized!"; echo; opt="";;
        esac
    done
fi

while read file
do
    [ ! -e "${DL_DIR}/${file}.done" ] || continue
    wget -nc "${SOURCE_MIRROR_URL}/${file}" -O "${DL_DIR}/${file}"
    [ $? -ne 0 ] || touch "${DL_DIR}/${file}.done"
done < <(cat "${src_pkg_lists[@]}" | sort -u)
