#!/usr/bin/env bash

set -e

[[ -e "./config.rc" ]] || {
    echo "Copy config.rc into the current directory before executing this script" >&2
    exit 1
}
source ./config.rc

export PATH="$builddir/bin:${systemPath:-/bin:/usr/bin}"

# $sourceStorage must be private so that curl/git/wget etc (of our own hacking)
# won't see it. If they see it, they won't look out the internet.
t="$sourceStorage"
export -n sourceStorage
sourceStorage="$t"

t="$networkLog"
export -n networkLog
networkLog="$t"


main()
{
    if [[ ! -e "$networkLog" ]]
    then
        echo "Network access log is required."
        echo "Modify config.rc and install online first so's to get the log."
        exit 1
    fi

    if [[ -z "$sourceStorage" ]]
    then
        echo "\$sourceStorage is not specified."
        echo "Modify config.rc."
        exit 1
    fi

    while getcmd
    do
        if [[ "${cmd[0]}" == "curl" ]]
        then
            run_curl "${cmd[@]}"
        elif [[ "${cmd[0]}" == "wget" ]]
        then
            run_wget "${cmd[@]}"
        elif [[ "${cmd[*]:0:2}" == "git archive" ]]
        then
            run_git_archive "${cmd[@]}"
        else
            echo "Cannot handle: ${cmd[*]}"
            exit 1
        fi
    done < "$networkLog"
}


cmd=()

getcmd()
{
    cmd=()
    local word
    while read -r word
    do
        if [[ "${word: -2}" == " \\" ]]
        then
            cmd+=("${word:0: -2}")
        else
            cmd+=("${word}")
            break
        fi
    done

    [[ ${#cmd[@]} -gt 0 ]]
}


run_curl()
{
    local args=("$@")
    local i
    local output=""

    for((i = 0; i < ${#args[@]}; ++i))
    do
        if [[ ${args[i]} == *"://"* ]]
        then
            echo "Fetching ${args[i]}"
            output="${sourceStorage}/${args[i]#*://}"
            break
        fi
    done

    if [[ -z "$output" ]]
    then
        echo "No url for curl: ${args[*]}"
        exit 1
    fi

    mkdir -p "$(dirname "$output")"
    "${args[@]}" > "$output"
}


run_wget()
{
    local args=("$@")
    local i

    for((i = 0; i < ${#args[@]}; ++i))
    do
        if [[ ${args[i]} == "-O" ]]
        then
            args=("${args[@]:0:i}" "${args[@]:i+2}")
            : $(( --i ))
        elif [[ ${args[i]} == "-O"* ]]
        then
            args=("${args[@]:0:i}" "${args[@]:i+1}")
            : $(( --i ))
        fi
    done

    mkdir -p "${sourceStorage}"
    pushd "${sourceStorage}"
    set +e
    "${args[@]}" -x -N
    set -e
    popd
}


run_git_archive()
{
    local args=("$@")
    local sum=( $(echo "${args[*]}" | sha1sum -b) )

    mkdir -p "${sourceStorage}"
    set +e
    echo "${args[@]}"
    "${args[@]}" > "${sourceStorage}/git-archive-${sum[0]}"
    set -e
}


main
