#!/bin/bash

sudo apt-get update
# Set up a crontab to execute system-setup after a reboot
crontab -l | grep system-setup
if [ $? -ne 0 ];then
  (crontab -l 2>/dev/null; echo "@reboot . /home/ubuntu/.profile; actev system-setup &>> /home/ubuntu/setup.log") | crontab
fi

USER="ubuntu"

# Install ffmpeg
ffmpeg -h
if [ $? -ne 0  ];then
  sudo apt-get install ffmpeg -y
fi

# Install docker-ce
docker -h
if [ $? -ne 0 ];then
  sudo apt-get install \
      apt-transport-https \
      ca-certificates \
      curl \
      software-properties-common -y

  curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
  sudo apt-key fingerprint 0EBFCD88

  sudo add-apt-repository -y \
     "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
     $(lsb_release -cs) \
     stable"
  sudo apt-get update
  sudo apt-get install docker-ce -y
  if [ $? -ne 0 ];then
    exit 1
  fi

  sudo usermod -a -G docker $USER
  sudo reboot
else
  docker image ls
  if [ $? -ne 0 ];then
    exit 1
  fi
fi

# Install nvidia-drivers
nvidia-smi -h
if [ $? -ne 0 ];then
  sudo add-apt-repository ppa:graphics-drivers -y
  sudo apt-get update
  sudo apt-get install nvidia-430 -y
  if [ $? -ne 0 ];then
    exit 1
  fi
  sudo reboot
else
  nvidia-smi
  if [ $? -ne 0 ];then
    exit 1
  fi
fi

# Install nvidia-docker
nvidia-docker -h
if [ $? -ne 0 ];then
  curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | \

  sudo apt-key add -
  distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
  curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | \
    sudo tee /etc/apt/sources.list.d/nvidia-docker.list
  sudo apt-get update

  sudo apt-get install nvidia-docker2 -y
  if [ $? -ne 0 ];then
    exit 1
  fi
  sudo pkill -SIGHUP dockerd
  sudo usermod -a -G docker $USER
  sudo reboot
else
  docker image ls
  if [ $? -ne 0 ];then
    exit 1
  fi
fi

# Install RC3D framework image
docker pull gitlab.kitware.com:4567/kwiver/r-c3d/framework-cli:meva-04-30-2020-combined
if [ $? -ne 0 ];then
  exit 1
fi

# Delete the crontab to avoid to reboot indefinitely
crontab -r
