#!/usr/bin/env julia

# process arguments
help = false
reports = String[]
absolute_tolerance = 1e-6
relative_tolerance = 1e-4

optind = 1

while optind <= length(ARGS)
    if ARGS[optind] == "-h" || ARGS[optind] == "--help"
        global help = true
    elseif ARGS[optind] in ("-a", "--absolute-tolerance")
        global optind += 1
        @assert optind <= length(ARGS)
        global absolute_tolerance = parse(Float64, ARGS[optind])
    elseif ARGS[optind] in ("-r", "--relative-tolerance")
        global optind += 1
        @assert optind <= length(ARGS)
        global relative_tolerance = parse(Float64, ARGS[optind])
    else
        push!(reports, ARGS[optind])
    end

    global optind += 1
end

ok = true
if length(reports) != 2
    global ok = false
    @error "Expected precisely 2 reports to compare"
end

if !ok
    global help = true
end

if help
    println(
        """Usage: fbcmt-run-frog [-h|--help] [<-a|--absolute-tolerance> tolerance] [<-r|--relative-tolerance> tolerance] <report1> <report2>""",
    )
    exit(ok ? 0 : 1)
end

if !isdir(reports[1]) || !isdir(reports[2])
    @error "reports must be stored in directories"
    global ok = false
end

if !ok
    exit(1)
end

# try to set up the environment
import Pkg
ips = Set(pkg.name for (_, pkg) in Pkg.dependencies())
inst_missing(x) =
    if !(x in ips)
        @info "Missing package '$x', trying to auto-install..."
        Pkg.add(x)
    end
inst_missing("FBCModelTests")

import FBCModelTests.FROG

@info "Initialization done, starting FROG comparison..." reports

# run the FROG
FROG.compare_reports_toplevel(reports[1], reports[2]; absolute_tolerance, relative_tolerance)
