#!/bin/sh
# this file requires sh over bash:
# https://github.com/textileio/go-textile/commit/d1190129727f6f2cb19183f348d67a8552352a2e
set -e
user=textile
repo="$TEXTILE_PATH"

if [ $(id -u) -eq 0 ]; then
	echo "Changing user to $user"
	# ensure folder is writable
	su-exec "$user" test -w "$repo" || chown -R -- "$user" "$repo"
	# restart script with new privileges
	exec su-exec "$user" "$0" "$@"
fi

# 2nd invocation with regular user
textile version

if [ -e "$repo/config" ]; then
	echo "Found IPFS fs-repo at $repo"
else
	wallet=$(textile wallet init)
	echo "$wallet"
	textile init $(echo "$wallet" | tail -n1) $INIT_ARGS
fi

# if the first argument is daemon
if [ "$1" = "daemon" ]; then
	shift
fi

exec textile daemon "$@"
