#!/usr/bin/env bash
#
# Runs tests
#

set -eu

cleanup() {
    [ -z "$temp_dir" ] || rm -rf "$temp_dir"
}

cargo test

temp_dir=""
trap cleanup EXIT
trap "exit 1" INT TERM QUIT
temp_dir="$(mktemp -d "/var/tmp/binup-test.XXXXXX")"

if [ "$(uname)" = Darwin ]; then
    arch=macos-arm64
else
    arch=linux-x64
fi

tool=binup
project="KonishchevDmitry/$tool"
release_matcher="$tool-$arch-*"

curl_args=()
if [ -n "${GITHUB_TOKEN-}" ]; then
    curl_args+=(--header "Authorization: Bearer $GITHUB_TOKEN")
fi

# FIXME(konishchev): Rewrite to mock of oldest/newest release
curl -L "${curl_args[@]}" "https://github.com/$project/releases/download/v0.4.0/$tool-$arch-v0.4.0.tar.bz2" \
    | tar -xjC "$temp_dir"
mv "$temp_dir"/{$tool,old-release}

cat > "$temp_dir/config.yaml" <<EOF
path: $temp_dir

tools:
  $tool:
    project: $project
    release_matcher: $release_matcher

  all-settings-test:
    project: $project
    release_matcher: $release_matcher
    binary_matcher: $tool
    changelog: https://github.com/$project/releases
    path: $temp_dir/custom
    post: touch $temp_dir/custom/post-install-marker
EOF

mkdir "$temp_dir/custom"

for command in install "install --force" upgrade; do
    cargo run -- --config "$temp_dir/config.yaml" $command

    (
        cd "$temp_dir"

        if [ "$command" = install ]; then
            ./binup --help > /dev/null
            ./custom/all-settings-test --help > /dev/null
            shasum binup custom/all-settings-test > checksums
        else
            shasum -c checksums > /dev/null
        fi

        cp -a old-release custom/all-settings-test
        rm custom/post-install-marker
    )
done