#!/bin/sh
# Smoke test: compile and run a Scala 3 program that uses enums, given
# instances and using clauses, extension methods, an opaque type and inline
# methods, with the installed commands (scalac-3, scala-3).
set -e

WORK="${AUTOPKGTEST_TMP:-$(mktemp -d)}"
cd "$WORK"

cat > Smoke.scala <<'X'
enum Shape:
  case Circle(r: Double)
  case Rect(w: Double, h: Double)

  def area: Double = this match
    case Circle(r)  => math.Pi * r * r
    case Rect(w, h) => w * h

object Units:
  opaque type Meters = Double
  object Meters:
    def apply(d: Double): Meters = d
  extension (m: Meters) def show: String = f"$m%.1f m"

trait Show[A]:
  def show(a: A): String

given Show[Int] with
  def show(a: Int): String = s"Int($a)"

given [A](using s: Show[A]): Show[List[A]] with
  def show(as: List[A]): String = as.map(s.show).mkString("[", ", ", "]")

def display[A](a: A)(using s: Show[A]): String = s.show(a)

extension (s: String) def shout: String = s.toUpperCase + "!"

inline def twice(inline x: Int): Int = x + x

@main def smoke(): Unit =
  import Units.*
  val shapes = List(Shape.Circle(1.0), Shape.Rect(2.0, 3.0), Shape.Circle(0.5))
  println(f"total area: ${shapes.map(_.area).sum}%.4f")
  println(display(List(1, 2, 3)))
  println("hello".shout)
  println(Meters(42.0).show)
  println(s"twice(21) = ${twice(21)}")
  println(s"version: ${scala.util.Properties.versionNumberString}")
X

cat > expected.txt <<'X'
total area: 9.9270
[Int(1), Int(2), Int(3)]
HELLO!
42.0 m
twice(21) = 42
X

scalac-3 -version
mkdir out
scalac-3 -d out Smoke.scala
scala-3 -cp out smoke > got.txt
cat got.txt
head -5 got.txt | diff -u expected.txt -
version=$(dpkg-query -W -f '${source:Upstream-Version}' scala3 | sed 's/+.*//')
grep -qx "version: $version" got.txt
# The same class files run on a plain JVM with only the standard library.
java -cp out:/usr/share/java/scala-library-3.jar smoke | grep -qx 'HELLO!'
echo "smoke test: PASS"
