#!/bin/sh
# Smoke test that Sage works without sagemath-dev, i.e. that none of the
# libraries, headers and tools only needed to compile code are needed for
# normal use. Each check touches one of Sage's backends.
set -e

if dpkg-query -W -f '${db:Status-Status}' sagemath-dev 2>/dev/null | grep -qx installed; then
	echo "sagemath-dev is installed, so this test would prove nothing" >&2
	exit 1
fi

export HOME="$AUTOPKGTEST_TMP"
export DOT_SAGE="$AUTOPKGTEST_TMP/.sage"
export OPENBLAS_NUM_THREADS=1
export OMP_NUM_THREADS=1
export LANG=C.UTF-8
cd "$AUTOPKGTEST_TMP"

echo "== sage command"
sage -c 'assert factor(2^64+1)[0][0] == 274177; print("ok")'

echo "== backends"
python3 - <<'EOF'
import os
import traceback
from sage.all import *

def check_pari():
    assert pari('factor(2^64+1)')[0][0] == 274177

def check_flint():
    x = ZZ['x'].gen()
    assert len((x**4 - 1).factor()) == 3

def check_ntl():
    x = PolynomialRing(GF(2), 'x', implementation='NTL').gen()
    assert len((x**8 - 1).factor()) == 1

def check_finite_fields():
    # givaro, and the Conway polynomial database
    assert GF(2**8, 'a').order() == 256
    assert GF(3**5, 'b', modulus='conway').modulus().degree() == 5

def check_linear_algebra():
    # linbox/fflas-ffpack, m4ri, m4rie, flint
    assert identity_matrix(GF(65521), 50).rank() == 50
    assert identity_matrix(GF(2), 100).rank() == 100
    assert identity_matrix(GF(4, 'c'), 10).rank() == 10
    assert matrix(ZZ, 2, [1, 2, 3, 4]).charpoly().list() == [-2, -5, 1]

def check_intervals():
    # mpfi, flint/arb
    assert 3.1415 < RIF(pi).lower() < RIF(pi).upper() < 3.1416
    assert CBF(0).exp() == 1

def check_libgap():
    assert libgap.SymmetricGroup(5).Size().sage() == 120
    assert SymmetricGroup(5).order() == 120

def check_gap_interface():
    assert gap('Size(SymmetricGroup(4))').sage() == 24

def check_libsingular():
    R = PolynomialRing(QQ, 'x,y')
    x, y = R.gens()
    assert len(R.ideal([x**2 - y, y**2 - x]).groebner_basis()) == 2

def check_singular_interface():
    assert singular('2+2').sage() == 4

def check_ecl_maxima_lib():
    from sage.libs.ecl import ecl_eval
    assert ecl_eval('(+ 1 2)').python() == 3
    x = var('x')
    assert bool(integrate(x**2, x) == x**3 / 3)

def check_maxima_interface():
    assert maxima('2+2').sage() == 4

def check_brial():
    B = BooleanPolynomialRing(2, 'a')
    a0, a1 = B.gens()
    assert a0 * a0 == a0

def check_eclib():
    E = EllipticCurve([0, 0, 1, -1, 0])
    assert E.rank(algorithm='mwrank_lib') == 1
    assert E.rank(algorithm='mwrank_shell') == 1
    assert EllipticCurve('11a1').conductor() == 11

def check_ecm():
    from sage.libs.libecm import ecmfactor
    n = 3 * next_prime(Integer(10)**20)
    # (True, factor, sigma) or (False, None)
    result = ecmfactor(n, 50)
    assert not result[0] or n % result[1] == 0
    assert prod(ecm.factor(Integer(2)**101 - 1)) == Integer(2)**101 - 1

def check_graphs():
    # libgap/bliss, cliquer, planarity, nauty
    P = graphs.PetersenGraph()
    assert P.automorphism_group().order() == 120
    assert P.clique_number(algorithm='Cliquer') == 2
    assert not P.is_planar()
    assert len(list(graphs.nauty_geng('4'))) == 11

def check_polyhedra():
    # ppl, cdd, palp
    assert polytopes.cube(backend='ppl').f_vector()[1] == 8
    assert polytopes.cube(backend='cdd').f_vector()[1] == 8
    assert LatticePolytope([(1, 0), (0, 1), (-1, -1)]).polar().nvertices() == 3

def check_milp():
    for solver in ['GLPK', 'HiGHS']:
        p = MixedIntegerLinearProgram(solver=solver)
        v = p.new_variable(integer=True, nonnegative=True)
        p.add_constraint(v[0] + v[1] <= 3.5)
        p.set_objective(v[0] + 2 * v[1])
        assert p.solve() == 6, solver

def check_knots():
    # libbraiding, libhomfly
    B = BraidGroup(3)
    assert B([1, 2, -1]).left_normal_form()
    assert Link(BraidGroup(2)([1, 1, 1])).homfly_polynomial()

def check_lrcalc():
    from sage.libs.lrcalc.lrcalc import lrcoef
    assert lrcoef([3, 2, 1], [2, 1], [2, 1]) == 2

def check_numerics():
    # gsl, scipy
    x = var('x')
    assert abs(numerical_integral(sin(x), 0, pi)[0] - 2) < 1e-10
    assert abs(find_root(cos, 0, 2) - pi / 2) < 1e-10

def check_sympy():
    x = var('x')
    assert bool(SR(x._sympy_()) == x)

def check_plots():
    # matplotlib, tachyon
    from sage.interfaces.tachyon import tachyon_rt
    plot(sin, 0, 1).save('plot.png')
    tachyon_rt(sphere().tachyon(), 'sphere.png', verbose=0)
    assert os.path.getsize('sphere.png') > 0

failed = []
for name, check in list(globals().items()):
    if name.startswith('check_'):
        try:
            check()
        except Exception:
            failed.append(name)
            traceback.print_exc()
        print(name, 'FAILED' if name in failed else 'ok', flush=True)
if failed:
    raise SystemExit('failed: ' + ', '.join(failed))
EOF
