#!/usr/bin/env bash
set -Eeuo pipefail

# From https://github.com/ipfs/go-ipfs/blob/ccef991a194beaedf009b1d0702b1150db3da0a6/cmd/ipfs/dist/install.sh
#
# Installation script for powergate. It tries to move $bin in one of the
# directories stored in $binpaths.

INSTALL_DIR="$(dirname "$0")"

pow="$INSTALL_DIR/pow"
binpaths="/usr/local/bin /usr/bin"

# This variable contains a nonzero length string in case the script fails
# because of missing write permissions.
is_write_perm_missing=""

for binpath in $binpaths; do
	if mv "$pow" "$binpath/$pow" 2>/dev/null; then
		echo "Moved $pow to $binpath"
		exit 0
	else
		if test -d "$binpath" && ! test -w "$binpath"; then
			is_write_perm_missing=1
		fi
	fi
done

echo "We cannot install $pow in one of the directories $binpaths"

if test -n "$is_write_perm_missing"; then
	echo "It seems that we do not have the necessary write permissions."
	echo "Perhaps try running this script as a privileged user:"
	echo
	echo "    sudo $0"
	echo
fi

exit 1