#!/bin/sh
# kcpp / ICPP installer (Linux x64).
#
#   ./install.sh              install into ~/.local/kcpp
#   ./install.sh /opt/kcpp    install somewhere else
#
# PATH is printed, not edited. A script that rewrites your shell profile
# unasked is how people end up with a login they cannot use.
set -e

SRC=$(cd "$(dirname "$0")" && pwd)
DEST=${1:-$HOME/.local/kcpp}

# OpenSSL 3 is a link-time dependency of kcpp. Checking here turns a loader
# error that appears only when the tool is first run into a sentence at
# install time that names the package to install.
if command -v ldconfig >/dev/null 2>&1; then
    if ! ldconfig -p 2>/dev/null | grep -q "libssl\.so\.3"; then
        echo "install.sh: libssl.so.3 was not found on this system." >&2
        echo "  kcpp links OpenSSL 3 and will not start without it:" >&2
        echo "    Debian/Ubuntu  apt-get install -y libssl3" >&2
        echo "    Fedora/RHEL    dnf install -y openssl-libs" >&2
        echo "  Continuing with the install; kcpp will not run until it is there." >&2
        echo >&2
    fi
fi

if [ ! -d "$SRC/linux-x64/bin" ]; then
    echo "install.sh: $SRC/linux-x64/bin is missing." >&2
    echo "If you unpacked the .zip, use the .tar.gz instead: the zip carries" >&2
    echo "neither the executable bit nor the libisqldll.so symlink." >&2
    exit 1
fi

echo "installing to $DEST"
mkdir -p "$DEST/bin" "$DEST/lib" "$DEST/doc" "$DEST/tools"

cp -f "$SRC"/linux-x64/bin/* "$DEST/bin/"
cp -f "$SRC"/linux-x64/lib/libisqldll.so.1 "$DEST/lib/"
ln -sf libisqldll.so.1 "$DEST/lib/libisqldll.so"
chmod 755 "$DEST"/bin/*

cp -rf "$SRC/doc/."      "$DEST/doc/"
cp -rf "$SRC/examples"   "$DEST/"
cp -rf "$SRC/lib/."      "$DEST/lib/"
cp -rf "$SRC/tools/."    "$DEST/tools/"
cp -f  "$SRC/README.txt" "$SRC/LICENSE" "$SRC/NOTICE" "$SRC/VERSION" "$DEST/"

# The tools load libisqldll.so by SONAME, so the library directory has to be
# findable at run time. LD_LIBRARY_PATH is used rather than ldconfig because
# this install needs no root.
cat <<EOF

installed.

add these two lines to your shell profile (~/.profile or ~/.bashrc):

    export PATH="$DEST/bin:\$PATH"
    export LD_LIBRARY_PATH="$DEST/lib:\$LD_LIBRARY_PATH"

then, in a new shell:

    icpp $DEST/examples/language/01_core_language.icpp

EOF
