#! /bin/sh

set -ex

srcdir="$(dirname "$0")"
test -z "$srcdir" && srcdir=.

cd "$srcdir"

clone_repo_commit() {
    if test -d "$2/.git"; then
        git -C "$2" reset --hard
        git -C "$2" clean -fd
        if ! git -C "$2" checkout $3; then
            rm -rf "$2"
        fi
    else
        if test -d "$2"; then
            set +x
            echo "error: '$2' is not a Git repository"
            exit 1
        fi
    fi
    if ! test -d "$2"; then
        git clone $1 "$2"
        if ! git -C "$2" checkout $3; then
            rm -rf "$2"
            exit 1
        fi
    fi
}

download_by_hash() {
    DOWNLOAD_COMMAND="curl -Lo"
    if ! command -v $DOWNLOAD_COMMAND >/dev/null 2>&1; then
        DOWNLOAD_COMMAND="wget -O"
        if ! command -v $DOWNLOAD_COMMAND >/dev/null 2>&1; then
            set +x
            echo "error: Neither curl nor wget found"
            exit 1
        fi
    fi
    SHA256_COMMAND="sha256sum"
    if ! command -v $SHA256_COMMAND >/dev/null 2>&1; then
        SHA256_COMMAND="sha256"
        if ! command -v $SHA256_COMMAND >/dev/null 2>&1; then
            set +x
            echo "error: Cannot find sha256(sum) command"
            exit 1
        fi
    fi
    if ! test -f "$2" || ! $SHA256_COMMAND "$2" | grep $3 >/dev/null 2>&1; then
        rm -f "$2"
        mkdir -p "$2" && rm -rf "$2"
        $DOWNLOAD_COMMAND "$2" $1
        if ! $SHA256_COMMAND "$2" | grep $3 >/dev/null 2>&1; then
            set +x
            echo "error: Cannot download file '$2' by hash"
            echo "incorrect hash:"
            $SHA256_COMMAND "$2"
            rm -f "$2"
            exit 1
        fi
    fi
}

clone_repo_commit \
    https://github.com/osdev0/freestnd-c-hdrs.git \
    freestnd-c-hdrs \
    21b59ecd6ef67bb32f893da8288ce08a324d1986

clone_repo_commit \
    https://github.com/osdev0/freestnd-cxx-hdrs.git \
    freestnd-cxx-hdrs \
    d604a4c5033a7a4d610ba41daab3c541be96b43e

clone_repo_commit \
    https://github.com/osdev0/cc-runtime.git \
    cc-runtime \
    576a01179f3298a4795b92f42c088f9f8800b56b

download_by_hash \
    https://github.com/limine-bootloader/limine/raw/4687a182be23939c2d9f15db970382dc353ed956/limine.h \
    src/limine.h \
    6879e626f34c1be25ac2f72bf43b083fc2b53887280bb0fcdaee790e258c6974
