#!/bin/sh
LUA_VERSION=5.4
test -f ../extra_cflags && . ../extra_cflags
CFLAGS="-Os -shared -fPIC ${CFLAGS} -I/usr/include/lua${LUA_VERSION}"

gcc -o crypt.so crypt.c ${CFLAGS} -L/usr/lib/lua${LUA_VERSION} -llua -lgcrypt

lua${LUA_VERSION} -e '
  c = require("crypt")
  io.write("== test ==\n")
  for _, algo in ipairs({"sha1", "sha256", "sha512", "sha3_256", "sha3_512", "blake2s_256", "blake2b_256", "blake2b_512"}) do
    assert(type(c[algo]("test", "raw")) == "string")
    assert(type(c[algo]("test", "b64")) == "string")
    assert(type(c[algo]("test", "b64url")) == "string")
    assert(type(c[algo]("test", "hex")) == "string")
    assert(type(c[algo]("test", "raw", "hmac")) == "string")
    assert(type(c[algo]("test", "b64", "hmac")) == "string")
    assert(type(c[algo]("test", "b64url", "hmac")) == "string")
    assert(type(c[algo]("test", "hex", "hmac")) == "string")
  end
  for i = 468, 579, 23 do
    bin = c.encrypt(string.format("test_%d", i), "password", string.format("nonce_%d", i), "raw")
    assert(c.decrypt(bin, "password", string.format("nonce_%d", i), "raw") == string.format("test_%d", i))
    b64 = c.encrypt(string.format("test_%d", i), "password", string.format("nonce_%d", i), "b64")
    assert(c.decrypt(b64, "password", string.format("nonce_%d", i), "b64") == string.format("test_%d", i))
    assert(c.decode(b64, "b64") == bin)
    assert(c.encode(bin, "b64") == b64)
    b64url = c.encrypt(string.format("test_%d", i), "password", string.format("nonce_%d", i), "b64url")
    assert(c.decrypt(b64url, "password", string.format("nonce_%d", i), "b64url") == string.format("test_%d", i))
    assert(c.decode(b64url, "b64url") == bin)
    assert(c.encode(bin, "b64url") == b64url)
    hex = c.encrypt(string.format("test_%d", i), "password", string.format("nonce_%d", i), "hex")
    assert(c.decrypt(hex, "password", string.format("nonce_%d", i), "hex") == string.format("test_%d", i))
    assert(c.decode(hex, "hex") == bin)
    assert(c.encode(bin, "hex") == hex)
    io.write(string.format("%3d: b64: %s, hex: %s\n  b64url: %s\n", i, b64, hex, b64url))
  end
  io.write(string.format("kdf: %s\n", c.kdf("password", "salt", "hex", 68)))
  -- test hash partial closure
  fnHpc = c.blake2b_512()
  fnHpc("te")
  fnHpc("st")
  hpc = fnHpc(nil)
  assert(c.blake2b_512("test") == hpc)
  io.write(string.format("hpc: %s\n", hpc))
  -- test setting encoding
   -- begin
  fnHpc1 = c.blake2b_512(nil, "b64")
  fnHpc1("test")
  hpc1 = fnHpc1()
   -- end
  fnHpc2 = c.blake2b_512()
  fnHpc2("test")
  hpc2 = fnHpc2(nil, "b64")
  assert(hpc1 == hpc2)
'

