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

bright_green='\u001b[32;1m'
reset_color='\033[0m'

color_bright_green(){
    echo -e "${bright_green}$@${reset_color}"
}

echo "sha resolves to __GIT_HASH__"

full_path="s3://zoox-web/firefly/tar/__GIT_HASH__.tar.gz"
echo "downloading from ${full_path}"

rm --recursive --force ~/firefly/
mkdir --parents ~/firefly/gateway

aws s3 cp "${full_path}" ~/firefly/

cd ~/firefly
tar -xf ~/firefly/__GIT_HASH__.tar.gz -C ~/firefly/gateway/
ln -s gateway/zoox/spectrum/apps/firefly/sh/deploy/run ~/firefly
ln -s gateway/zoox/spectrum/apps/firefly/sh/deploy/run_gateway ~/firefly

install_packages(){
  echo "checking installed packages"
  packages=("python2.7" "python3.6" "sshpass")
  need_install=false
  for pkg in ${packages[@]}; do
      if ! dpkg -s $pkg >/dev/null 2>&1; then
        echo "${pkg} needs install"
        need_install=true
      fi
  done
  if ${need_install}; then
      sudo add-apt-repository ppa:deadsnakes/ppa -y
      sudo apt-get update
      # python to start ros
      # python3.6 to run py_binaries
      # sshpass for collect_can_logs

      sudo apt install -y \
        python2.7 \
        python3.6 \
        sshpass
  fi

}

install_packages
# TODO should be in OS image
mkdir --parents ~/.log/  # this was already here but adding it just in case
mkdir --parents ~/.log/python/  # was missing

curl  http://firefly.web.zooxlabs.com/moth.txt
echo "
                 __ _           __ _
                / _(_)         / _| |
                | |_ _ _ __ ___| |_| |_   _
                |  _| | '__/ _ \  _| | | | |
                | | | | | |  __/ | | | |_| |
                |_| |_|_|  \___|_| |_|\__, |
                                    __/   /
                                    |___/ "

color_bright_green "Firefly installed! Run the gateway using:"
echo "    ~/firefly/run_gateway"
color_bright_green "Then, in another window, launch the UI:"
echo "    ~/firefly/run"

