#!/usr/bin/env sh

# Usage: ./dl_and_verify.sh <sha256_file> <base_url>
# Example: ./dl_and_verify.sh SHA256 https://olitb.net/pro/uni29/lattices/

set -eu

sha256_file="$1"
base_url="$2"

# Check if sha256sum is available
if ! command -v sha256sum >/dev/null 2>&1; then
    echo "Error: sha256sum command not found." >&2
    exit 1
fi

# Check if wget or curl is available
if ! command -v wget >/dev/null 2>&1 && ! command -v curl >/dev/null 2>&1; then
    echo "Error: neither wget nor curl found." >&2
    exit 1
fi

download_file() {
    local url="$1"
    local dest="$2"
    if command -v wget >/dev/null 2>&1; then
        wget -q -O "$dest" "$url"
    else
        curl -s -o "$dest" "$url"
    fi || echo "download failed"
}

# Read the SHA256 file line by line
while IFS= read -r line; do
    # Skip empty lines and comments
    [ -z "$line" ] && continue
    [ "$(echo "$line" | cut -c1)" = "#" ] && continue

    # Extract hash and filename
    hash="$(echo "$line" | awk '{print $1}')"
    filename="$(echo "$line" | awk '{print $2}')"

    # Check if file exists and hash matches
    if [ -f "$filename" ]; then
        current_hash="$(sha256sum "$filename" | awk '{print $1}')"
        if [ "$current_hash" = "$hash" ]; then
            echo "File $filename exists and hash matches. Skipping."
            continue
        else
            echo "File $filename exists but hash does not match. Redownloading."
        fi
    else
        echo "File $filename does not exist. Downloading."
    fi

    # Create directory if it does not exist
    dir="$(dirname "$filename")"
    if [ -n "$dir" ] && [ ! -d "$dir" ]; then
        echo "Creating directory: $dir"
        mkdir -p "$dir"
    fi
    # Download the file
    download_file "${base_url}${filename}" "$filename"

    # Verify the downloaded file
    new_hash="$(sha256sum "$filename" | awk '{print $1}')"
    if [ "$new_hash" != "$hash" ]; then
        echo "Error: Downloaded file $filename does not match expected hash." >&2
        rm -f "$filename"
        exit 1
    fi
done < "$sha256_file"

echo "All files are up to date and verified."
