#!/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")"

tool=binup
project="KonishchevDmitry/$tool"

if [ "$(uname)" = Darwin ]; then
    release_matcher="$tool-macos-arm64-*"
else
    release_matcher="$tool-linux-*"
fi

github_config=""
if [ -n "${GITHUB_TOKEN-}" ]; then
    github_config="github: {token: $GITHUB_TOKEN}"
fi

(
    cd "$temp_dir"
    mkdir bin custom-bin

    cat > old-release-mock <<EOF
#!/bin/bash
echo "$tool 0.1.0"
EOF

    cat > new-release-mock <<EOF
#!/bin/bash
echo "$tool 100.0.0"
EOF

    chmod a+x old-release-mock new-release-mock
    touch --no-create --date 2024-07-29 old-release-mock

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

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

  up-to-date:
    project: $project
    release_matcher: $release_matcher
    binary_matcher: $tool

  upgradable:
    project: $project
    release_matcher: $release_matcher
    binary_matcher: $tool
    changelog: https://github.com/$project/releases
    path: $temp_dir/custom-bin
    post: touch $temp_dir/post-install-marker

$github_config
EOF
)

for command in install "install --force" upgrade; do
    cp -a "$temp_dir/new-release-mock" "$temp_dir/bin/up-to-date"
    cp -a "$temp_dir/old-release-mock" "$temp_dir/custom-bin/upgradable"

    cargo run -- --config "$temp_dir/config.yaml" $command

    (
        cd "$temp_dir"

        "bin/$tool" --help > /dev/null

        if [ "$command" = "install --force" ]; then
            cmp bin/up-to-date "bin/$tool"
        else
            cmp bin/up-to-date new-release-mock
        fi

        if [ "$command" = install ]; then
            shasum "bin/$tool" > checksum

            cmp custom-bin/upgradable old-release-mock
            if [ -e post-install-marker ]; then
                echo "An unexpected call of post-install script." >&2
                exit 1
            fi
        else
            shasum -c checksum > /dev/null
            cmp custom-bin/upgradable "bin/$tool"
            rm post-install-marker
        fi
    )
done