#!/usr/bin/env bash
# Copyright (c) 2020 The Toltec Contributors
# SPDX-License-Identifier: MIT

set -e
source scripts/package-lib

usage="$0 [OPTION]... LOCALREPO [REMOTEREPO]

Check that the LOCALREPO and REMOTEREPO repositories are identical.
If REMOTEREPO is omitted, 'https://toltec-dev.org/testing' is used.

Options:

    -h              Show this help message."

helpflag=

while getopts hf name; do
    case $name in
        h) helpflag=1 ;;
        *) error "Invalid option. Use the -h flag for more information." ;;
    esac
done

shift $((OPTIND - 1))

if [[ -n $helpflag ]]; then
    echo "$usage"
    exit
fi

if [[ $# -eq 0 ]]; then
    error "Missing LOCALREPO argument. Use the -h flag for more information."
fi

localrepo="$1"
remoterepo="https://toltec-dev.org/testing"

if [[ $# -eq 2 ]]; then
    remoterepo="$2"
fi

if [[ $# -gt 2 ]]; then
    error "Extraneous arguments. Use the -h flag for more information."
fi

differs=

if [[ ! -f "$localrepo"/Packages ]]; then
    error "Local repository is missing packages index"
fi

for localfile in "$localrepo"/*; do
    file="$(realpath --relative-to="$localrepo" "$localfile")"
    remotefileurl="$remoterepo"/"$file"

    section "Checking $file"

    remotefile="$(mktemp)"
    rsecurl "$remotefileurl" -o "$remotefile"

    if ! tardiff "$localfile" "$remotefile" "local $file" "remote $file"; then
        differs=yes
    fi

    rm "$remotefile"
done

if [[ -n $differs ]]; then
    error "Some files differ"
else
    section "Successful"
fi
