#!/bin/sh

set -e

TP_URL="https://download.tizen.org/tp/0.3.7/tp"

INSTALL_DIR="$HOME/bin"

detect_shell_rc() {
  if [ -n "$ZSH_VERSION" ]; then
    echo "$HOME/.zshrc"
  elif [ -n "$BASH_VERSION" ]; then
    echo "$HOME/.bashrc"
  elif [ -f "$HOME/.bash_profile" ]; then
    echo "$HOME/.bash_profile"
  else
    echo "$HOME/.profile"
  fi
}

mkdir -p "$INSTALL_DIR"

echo "Downloading tp to $INSTALL_DIR/tp..."
curl -fsSL "$TP_URL" -o "$INSTALL_DIR/tp"

chmod +x "$INSTALL_DIR/tp"

SHELL_RC="$(detect_shell_rc)"
if ! echo "$PATH" | grep -q "$INSTALL_DIR"; then
  echo "Adding $INSTALL_DIR to PATH in $SHELL_RC"
  echo "\n# Added by tp installer" >> "$SHELL_RC"
  echo "export PATH=\"\$HOME/bin:\$PATH\"" >> "$SHELL_RC"
  echo "Installation complete. Restart your shell or run 'source $SHELL_RC' to use 'tp'."
fi

echo ""
echo "To verify the installation, try running:"
echo "  \$ tp --version"
echo "If you see an error, please check that \$HOME/bin is in your PATH."
echo "For more information, see https://docs.tizen.org/platform/reference/tp-usage/"
echo ""
echo "Initialize your tp configuration with:"
echo ""
echo "  \$ tp init"
