#!/bin/sh
set -e
# Paths
dir_build="$PWD/build"
dir_source="$PWD/source"
dir_install="$PWD/install"
# Some printing functions
show_help() {
echo "This astronaut will help you build some satellites.
Just describe what he's got to do in a satellite file.
Usage: $0 [-s 
] [-b ] [-i ] 
-s  Set source directory
-b  Set build directory [WARNING: Will be deleted before build]
-i  Set install directory"
}
msg() {
    echo "=> $@"
}
exiterr() {
    echo "===> Houston, we've got a problem: $@" 1>&2
    exit 1
}
# Gather info
while getopts "h?s:b:i:" opt; do
    case "$opt" in
        h|\?)
            show_help
            exit 0
            ;;
        s)
            dir_source="$(realpath "$OPTARG")"
            ;;
        b)
            dir_build="$(realpath "$OPTARG")"
            ;;
        i)
            dir_install="$(realpath "$OPTARG")"
            ;;
    esac
done
shift $((OPTIND-1))
[ "$1" = "--" ] && shift
if [ ! "$1" ]; then
    show_help
    exit 1
fi
satellite="$(realpath "$1")"
if [ ! -f "$satellite" ]; then
    exiterr "Can't find satellite file"
fi
# Configuration
cmd_download="curl -#L -o {dst} {src}"
cmd_extract="tar xf {src}"
# Tools for the astronaut
mksum() {
    echo $(md5sum "$@" 2> /dev/null | cut -d' ' -f1)
}
download() {
    local name="$(basename "$1")"
    local path="$dir_source/$name"
    local checksum=""
    if [ "$2" -a -f "$path" ]; then
        checksum="$(mksum "$path")"
    fi
    if [ ! -f "$path" -o "$checksum" != "$2" ]; then
        msg "Downloading $name"
        if [ "$3" ]; then
            local cmd="$3"
        else
            local cmd="$cmd_download"
        fi
        $(echo "$cmd" | sed -e 's@{dst}@'"$path"'@g' -e 's@{src}@'"$1"'@g')
        checksum="$(mksum "$path")"
        if [ "$2" -a "$checksum" != "$2" ]; then
            msg "Checksum: $checksum"
            exiterr "Checksum failed"
        fi
    fi
}
extract() {
    msg "Extracting $1"
    if [ "$2" ]; then
        local cmd="$2" 
    else
        local cmd="$cmd_extract"
    fi
    $(echo "$cmd" | sed -e 's@{src}@'"$dir_source/$1"'@g')
}
dlextract() {
    download "$1" "$2"
    extract "$(basename "$1")"
}
extrafile() {
    cp "$(dirname "$satellite")/$1" "$dir_build/$1"
}
# Create the satellite
rm -rf "$dir_build"
mkdir -p "$dir_source"
mkdir -p "$dir_build"
mkdir -p "$dir_install"
cd "$dir_build"
. "$satellite"