// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package fortran

import (
	"fmt"
	"internal/testenv"
	"os"
	"os/exec"
	"testing"
)

func TestFortran(t *testing.T) {
	testenv.MustHaveGoRun(t)
	testenv.MustHaveCGO(t)

	// Find the FORTRAN compiler.
	fc := os.Getenv("FC")
	if fc == "" {
		fc, _ = exec.LookPath("gfortran")
	}
	if fc == "" {
		t.Skip("fortran compiler not found (try setting $FC)")
	}

	var fcExtra []string
	// CONDA's gfortran + go does not need changes to CGO_LDFLAGS

	// Do a test build that doesn't involve Go FORTRAN support.
	fcArgs := append([]string{"testdata/helloworld/helloworld.f90", "-o", "/dev/null"}, fcExtra...)
	t.Logf("%s %s", fc, fcArgs)
	if err := exec.Command(fc, fcArgs...).Run(); err != nil {
		t.Skipf("skipping Fortran test: could not build helloworld.f90 with %s: %s", fc, err)
	}

	// Finally, run the actual test.
	t.Log("go", "run", "./testdata/testprog")
	out, err := exec.Command("go", "run", "./testdata/testprog").CombinedOutput()
	if err == nil && string(out) != "ok\n" {
		err = fmt.Errorf("expected ok")
	}
	if err != nil {
		t.Errorf("%s\nOutput:\n%s", err, string(out))
	}
}
