#!/usr/bin/env bash

# ビルドした sile 一式をインストールするディレクトリです。
# ご自由に変更してください。

export MY_SILE_DIR=$HOME/local/sile

# 1. ソースダウンロード
[ -d sile ] || git clone --recurse-submodules https://github.com/sile-typesetter/sile.git
if [ ! -d sile ] ; then
    echo ERROR: git clone was failed
    exit
fi

cd sile

# 2. bootstrap
[ -e configure ] || ./bootstrap.sh


# 3. 環境変数のリセット/セット
# PATH のサニタイズ
[ -z "$HOMEBREW_PREFIX" ] && HOMEBREW_PREFIX=$(brew --prefix)
export PATH="$HOMEBREW_PREFIX/bin:/usr/bin:/bin:/usr/sbin:/sbin"

unset CPPFLAGS LDFLAGS PKG_CONFIG_PATH

function myFilePathSearch() {
    find -L $HOMEBREW_PREFIX/opt -maxdepth 4 -type d -iname $1 \
		| grep -e icu4c/ -e openssl/ -e luajit/ -e libpng/ -e libpng/ \
		| sort -u
}

export PKG_CONFIG_PATH=$( myFilePathSearch pkgconfig |                    tr '\n' ':' | sed 's/:$//' )
export CPPFLAGS=$(        myFilePathSearch include   | sed -e 's/^/-I/' | tr '\n' ' ' | sed 's/ $//' )
export LDFLAGS=$(         myFilePathSearch lib       | sed -e 's/^/-L/' | tr '\n' ' ' | sed 's/ $//' )
# 「_luaL_checkinteger」のエントリを探すため /opt/homebrew/opt/luajit/lib/libluajit-5.1.2.dylib

# CPPFLAGS 補正理由
# 上記の CPPFLAGS の処理で -I/opt/homebrew/opt/luajit/include が登録されるが
# 「-I/opt/homebrew/opt/luajit/include」では「#include <lua.h>」の構文で
# 該当ファイルを探し出せないという不具合を正すため
#    /opt/homebrew/opt/luajit/include/
#    └── luajit-2.1
#        ├── lauxlib.h
#        ├── lua.h
#        ├── lua.hpp
#        ├── luaconf.h
#        ├── luajit.h
#        └── lualib.h

export CPPFLAGS="$(
    find -L ${HOMEBREW_PREFIX}/opt -maxdepth 4 -iname lua.h -o -iname luajit.h \
    | grep luajit | xargs -L1 dirname | sort -u | sed 's/^/-I/' ) $CPPFLAGS"

echo PATH            ; echo $PATH            | tr ':' '\n' | nl
echo PKG_CONFIG_PATH ; echo $PKG_CONFIG_PATH | tr ':' '\n' | nl
echo CPPFLAGS        ; echo $CPPFLAGS        | tr ' ' '\n' | nl
echo LDFLAGS         ; echo $LDFLAGS         | tr ' ' '\n' | nl

# 4. 前回のビルド成果物を掃除
if [ -e Makefile ] ; then
    make clean
    [ -n "$MY_SILE_DIR" ] && make uninstall
fi

# 5. configure を実行（環境変数は今のまま引き継がれます）
./configure \
    --prefix="$MY_SILE_DIR"     \
    FCMATCH=true                \
    --disable-silent-rules      \
    --disable-static            \
    --disable-embeded-resources \
    --with-system-lua-sources
  # --enable-developer-mode
  # --with-system-luarocks

# 6. ビルド/ make

# Rust 側の古いビルド設定（静的リンクのキャッシュ）をクリア
cargo clean -p sile
## make

# make（RUSTFLAGS に luajit の動的リンクも明示）
export RUSTFLAGS="-L$HOMEBREW_PREFIX/opt/luajit/lib -lluajit-5.1 -C link-arg=-Wl,-export_dynamic"
[ -e Makefile ] && make -s LDFLAGS="$LDFLAGS -Wl,-export_dynamic" all

# 7. 簡易チェック
[ -e ./sile ]                                && otool -L ./sile
[ -e ./lua_modules/lib/lua/5.1/lua-utf8.so ] && otool -L ./lua_modules/lib/lua/5.1/lua-utf8.so

# 8. インストール
make install

# 9. 簡易TEST

cat << _E_O_F_ > test.sil
\begin{document}
Hello SILE world!
\end{document}
_E_O_F_

[ -e ./sile ] && ./sile test.sil
if [ -e test.pdf ] ; then
    echo "万歳 sile インストール成功"
    echo "$MY_SILE_DIR/bin を PATH に追加してね"
    open test.pdf
fi
exit
