#!/bin/sh
#
#   Export a MUX flatfile from the SQLite database.
#
#   Usage: db_unload <basename> <flatfile> [-C <comsys.db>] [-m <mail.db>]
#
#   Example: db_unload netmux netmux.flat
#            db_unload netmux netmux.flat -C comsys.db -m mail.db
#
#   The SQLite database (<basename>.sqlite) is always read from next to this
#   script, i.e. from the game's data/ directory, so it matches the server's
#   configured input_database no matter which directory you run this from.
#   Output flatfile arguments are resolved relative to your current directory.
#
#   Note: The server should not be running during export.
#

#
#   Runs from the game directory rather than data/, and passes the basename
#   as data/<basename>.  dbconvert's init_modules() loads ./bin/engine.so
#   relative to the CURRENT DIRECTORY, so running from data/ made it look for
#   data/bin/engine.so and fail with "Failed to initialize modules" (#1336).
#   This mirrors what db_unload.bat/db_load.bat do on Windows.
#
#   On macOS the old form happened to work: dyld consults DYLD_LIBRARY_PATH
#   even for a path containing a slash, so ./bin/engine.so was rescued by the
#   export below.  Linux's ld.so does not do that for slash-containing paths,
#   so the failure was real there and merely masked here.
#
# Directory this script lives in (the game's data/ directory).
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)

# Directory the caller invoked us from, for resolving relative file arguments.
INVOKE_DIR=$(pwd)

abspath() {
    case "$1" in
        /*) printf '%s\n' "$1" ;;
        *)  printf '%s\n' "$INVOKE_DIR/$1" ;;
    esac
}

usage() {
    echo "Usage: $0 <basename> <flatfile> [-C <comsys.db>] [-m <mail.db>]"
    echo "  e.g. $0 netmux netmux.flat"
    echo "       $0 netmux netmux.flat -C comsys.db -m mail.db"
    exit 1
}

[ $# -ge 2 ] || usage
BASENAME="$1"
FLATFILE=$(abspath "$2")
shift 2

COMSYS=
MAIL=
while [ $# -ge 1 ]; do
    case "$1" in
        -C) [ $# -ge 2 ] || usage; COMSYS=$(abspath "$2"); shift 2 ;;
        -m) [ $# -ge 2 ] || usage; MAIL=$(abspath "$2");   shift 2 ;;
        *)  usage ;;
    esac
done

GAME_DIR=$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd)
BIN="$GAME_DIR/bin"
LD_LIBRARY_PATH="$BIN"; export LD_LIBRARY_PATH
DYLD_LIBRARY_PATH="$BIN"; export DYLD_LIBRARY_PATH

cd "$GAME_DIR" || exit 1

echo "Exporting from: $SCRIPT_DIR/$BASENAME.sqlite"

set -- -d "data/$BASENAME" -u -o "$FLATFILE"
[ -n "$COMSYS" ] && set -- "$@" -C "$COMSYS"
[ -n "$MAIL" ]   && set -- "$@" -m "$MAIL"

"$BIN/dbconvert" "$@"
exit $?
