# Common variables
download_dir=${DOWNLOAD_DIR:-$base_dir/download}

# Common tasks

# Downloads all the source files mentioned in $source
download() {
    mkdir -p $download_dir
    for s in $source; do
        url=${s%#*} # Remove hash part
        path=$download_dir/${url##*/}
        path=${path%%\?*} # Remove query part
        hash=${s##*#}
        hash=${hash%"$url"}

        # Download:
        if [ -e $s ]; then
            if [ -e $path ]; then
                rm -rf $path
            fi

            cp -a $s $path
        elif [ $path != ${path%.git} ]; then
            if [ -e "$path" ]; then
                git --git-dir="$path" fetch -f "$url" +refs/heads/*:refs/heads/*
            else
                git clone --bare "$url" "$path"
            fi
        else
            if [ ! -e "$path" ]; then
                curl -L "$url" > "$path"
            fi

            # Checksum:
            output=$(shasum "$path")
            output="${output%% *}"
            if [ -n "$hash" -a "$hash" != "$output" ]; then
                echo "error: checksum failed on $(relative path): expected $hash, got $output"
                echo "moving $(relative $path) to $(relative $path).fail"
                mv "$path" "$path.fail"
                return 1
            else
                echo "SHA1 $(relative $path) = $output"
            fi
        fi
    done
}
task download

# Unpacks the source files mentioned in $source with the .tar.* extension
unpack() {
    for s in $source; do
        url=${s%#*} # Remove hash part
        path=$download_dir/${url##*/}
        path=${path%%\?*} # Remove query part
        hash=${s##*#}
        hash=${hash%"$url"}

        # Unpack:
        if [ -e $s ]; then
            if [ -e $work_dir ]; then
                rm -rf $work_dir
            fi

            cp -a $path $work_dir
        elif [ $path != ${path%.git} ]; then
            # Check out using git:
            for i in {0..7}; do
                # Parallel checkouts will fail, so wait:
                if [ -e "$path/index.lock" ]; then sleep 1; fi
            done
            git --git-dir="$path" --work-tree="$work_dir" reset --hard "${hash:-master}"
        elif [ $path != ${path%.tar*} -o $path != ${path%.tgz} ]; then
            # Unpack using tar:
            echo "Unpacking $(relative $path) to $(relative $work_dir)..."
            tar -C "$work_dir" -xmf "$path"
        fi
    done
}
task unpack download

# Writes the full (recursive) dependency list for a package
write_deps() {
    for dep in $depends; do
        echo $dep
        cat $build_dir/$dep/depends
    done | sort | uniq > depends
}
task write-deps $(for dep in $depends; do echo $dep.write-deps; done)

clean() {
    rm -rf $work_dir
}
task clean
