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

# Public facing script that can be used to provision a new machine
# For developers:
#   wget -O - https://kansas.remedyrobotics.com/scripts/provision.sh | bash
# For robot1 user:
#   USER_OVERRIDE=robot1 bash -c 'wget -O - https://kansas.remedyrobotics.com/scripts/provision.sh | bash'

# Check if USER_OVERRIDE is set
if [ -n "${USER_OVERRIDE:-}" ]; then
  D_USER="${USER_OVERRIDE}"
else
  D_USER="${USER:-$(whoami)}"
fi

echo "Provisioning for user: ${D_USER}"

D_HOME="/home/${D_USER}"
CODE_HOME="${D_HOME}/code"
mkdir -p "${CODE_HOME}"

sudo apt update
sudo apt install -y git landscape-client openssh-server vim zsh

if ! command -v google-chrome &> /dev/null; then
  wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb -O /tmp/google-chrome-stable_current_amd64.deb
  sudo apt install /tmp/google-chrome-stable_current_amd64.deb
else
  echo "Google Chrome is already installed"
fi

if ! command -v code &> /dev/null; then
  wget 'https://code.visualstudio.com/sha/download?build=stable&os=linux-deb-x64' -O /tmp/code_latest_amd64.deb
  sudo apt install /tmp/code_latest_amd64.deb -y
else
  echo "Visual Studio Code is already installed"
fi

# Setup ssh
# Check if the user has an existing SSH key
if [ -f "${D_HOME}/.ssh/id_ed25519" ]; then
  echo "SSH key already exists"
else
  ssh-keygen -t ed25519 -C "${D_USER}@remedyrobotics.com"
  eval "$(ssh-agent -s)"
  ssh-add "${D_HOME}/.ssh/id_ed25519"
fi

echo "Add the following SSH key to your GitHub account:"
cat "${D_HOME}/.ssh/id_ed25519.pub"
read -r -p "Press enter to continue"

if [ -d "${CODE_HOME}/rc" ]; then
  echo "rc repository already exists"
  cd "${CODE_HOME}/rc"
  git fetch
  git checkout feature/jazzy
  git pull
else
  git clone git@github.com:Remedy-Robotics/rc.git "${CODE_HOME}/rc" -b feature/jazzy
  cd "${CODE_HOME}/rc"
fi
git submodule update --init

./scripts/install-nvidia-driver.sh

./scripts/install.sh

read -r -p "Do you want to install production extras? (y/n) " yn
if [[ $yn =~ ^[Yy]$ ]]; then
  echo "Installing production extras..."
  ./scripts/install-prod-extras.sh
else
  echo "Skipping production extras installation."
fi

echo "Provisioning complete!"