#!/bin/sh

#
# the directory where Teleport binaries will be located
#
BINDIR=/usr/local/bin

#
# the directory where Teleport will keep its state/data
#
VARDIR=/var/lib/teleport

#
# the directory where Teleport .app bundles will be installed
#
APPS_DIR=/Applications

[ ! $(id -u) != "0" ] || { echo "ERROR: You must be root"; exit 1; }

#
# What operating system is the user running?
#
unameOut="$(uname -s)"
case "${unameOut}" in
    Linux*)     machine=linux;;
    Darwin*)    machine=darwin;;
    CYGWIN*)    machine=cygwin;;
    MINGW*)     machine=minGw;;
    *)          machine="UNKNOWN:${unameOut}"
esac

[ "$machine" == "darwin" ] || { echo "ERROR: This script is intended for darwin this machine is $machine"; exit 1; }

echo "Starting Teleport installation..."
cd $(dirname $0)
mkdir -p $VARDIR $BINDIR
cp -f teleport tbot fdpass-teleport $BINDIR/ || exit 1
cp -rf tsh.app/ "$APPS_DIR"/tsh.app/ || exit 1
cp -rf tctl.app/ "$APPS_DIR"/tctl.app/ || exit 1


# If tsh exists and is not a link, make a backup.
if [ -f "$BINDIR/tsh" ] && [ ! -L "$BINDIR/tsh" ]; then
rm -f "$BINDIR/tsh.bak"
mv "$BINDIR/tsh" "$BINDIR/tsh.bak"
fi

# Link package to $BINDIR.
rm -f "$BINDIR/tsh"  # in case link exists
ln -s "$APPS_DIR/tsh.app/Contents/MacOS/tsh" "$BINDIR/tsh"

# If tctl exists and is not a link, make a backup.
if [ -f "$BINDIR/tctl" ] && [ ! -L "$BINDIR/tctl" ]; then
rm -f "$BINDIR/tctl.bak"
mv "$BINDIR/tctl" "$BINDIR/tctl.bak"
fi

# Link package to $BINDIR.
rm -f "$BINDIR/tctl"  # in case link exists
ln -s "$APPS_DIR/tctl.app/Contents/MacOS/tctl" "$BINDIR/tctl"


echo "Teleport binaries have been copied to $BINDIR"
echo ""
echo "Thanks for installing Teleport."
echo ""
echo "Is it OK if we collect some info about your install?"
echo "Please run this command to send in a survey."
echo "Optional: Replace email to join our newsletter and get a swag package."
echo "$ curl -X POST https://usage.teleport.dev -F OS=${machine} -F use-case=\"access my ...\" -F email=\"alice@example.com\""
echo ""
echo "Otherwise, ignore!"
