APP=lua53
VERSION=5.3.5
BUILD=1sml
HOMEPAGE='https://www.lua.org/home.html'
DOWNLOAD='https://www.lua.org/ftp/lua-5.3.5.tar.gz'
DESC="powerful, fast, light-weight, embeddable scripting language"
REQUIRES="readline"

build() {
  mkandenterbuilddir
  rm -rf lua-$VERSION

  tar xf $SRCDIR/lua-$VERSION.tar.?z*
  cd lua-$VERSION
  fixbuilddirpermissions

  patch -p1 < $SRCDIR/CVE-2019-6706-use-after-free-lua_upvaluejoin.patch

  eval $(sed -ne '/^\(V\|R\)= /s, ,,p' Makefile)

  sed -i \
    -e '/^INSTALL_TOP= /s,\(/\).*,\$(DESTDIR)\1,' \
    -e '/^INSTALL_INC= /s,include,&/lua\$V,' \
    -e '/^TO_BIN= /s,luac\?,&\$V,g' \
    -e '/^TO_LIB= /s,liblua,&\$V,' \
    Makefile

  sed -i \
    -e '/^CFLAGS= /s,-O2,'"$CFLAGS"',' \
    -e '/-DLUA_USE_LINUX.*-Wl,-E -ldl -lreadline/s|-lreadline|& -lcurses|' \
    -e '/^LUA_A=/s,liblua,&'"$V"',' \
    -e '/^LUA_T=/s,lua,&'"$V"',' \
    -e '/^LUAC_T=/s,luac,&'"$V"',' \
    src/Makefile

  make linux
  make install INSTALL_MAN="$PKG/share/man/man1" DESTDIR=$PKG

  # Now let's build the shared library
  mkdir -p shared && cd shared
  ar -x $PKG/lib/liblua$V.a
  gcc -ldl -lreadline -lncurses -lterminfo -lm -shared *.o -o liblua$V.so.$R
  cp -a liblua$V.so.$R $PKG/lib
  ( cd $PKG/lib
    ln -s liblua$V.so.$R liblua$V.so.$V
    ln -s liblua$V.so.$R liblua$V.so.${V%??}
    ln -s liblua$V.so.$R liblua$V.so
  )
  cd - >/dev/null

  mkdir -p $PKG/lib/pkgconfig
  cd $PKG/lib/pkgconfig
  sed \
    -e '/^V= /s, .*, '"$V"',' \
    -e '/^R= /s, .*, '"$R"',' \
    -e '/^prefix= /s,\(/\).*,\1,' \
    -e '/^INSTALL_INC= /s,include,&/lua\${V},' \
    -e '/^includedir=/s,/include,&/lua\${V},' \
    $SRCDIR/lua.pc.in > lua$V.pc
  ln -s lua$V.pc lua-$V.pc
  mkfinalpkg
  ln -s lua$V.pc lua${V%.?}${V#?.}.pc
  cd - >/dev/null

  cd $PKG/share/man/man1
  mv lua.1 lua$V.1
  mv luac.1 luac$V.1
  cd - >/dev/null

  mkfinalpkg
}

SHA512SUMS="
4f9516acc4659dfd0a9e911bfa00c0788f0ad9348e5724fe8fb17aac59e9c0060a64378f82be86f8534e49c6c013e7488ad17321bafcc787831d3d67406bd0f4  lua-5.3.5.tar.gz
fde7f5f5a184cd393665c7c8c7ba3c728e1413df5f63dbe60855af13ddd313d9300720298534f4312638ddf59fa678a38f708bce622dd7a2298b4ed87c068ae7  CVE-2019-6706-use-after-free-lua_upvaluejoin.patch
"
