#!/bin/bash -x
#
# add's docker official ppa package source for Docker engine and install it
# does not include docker-compose or docker-machine
# run as root
#

# ensure we have tools to install
apt-get -y install \
  apt-transport-https \
  ca-certificates \
  curl

# add official package repo key
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

# add official package repo
# change stable on the last line to edge for beta-like monthly releases
# stable releases are quarterly
add-apt-repository \
       "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
       $(lsb_release -cs) \
       stable"

# remove lxcfs, as we don't need it if we're doing docker
service lxcfs stop
apt-get remove -y -q lxc-common lxcfs lxd lxd-client

apt-get update -q
apt-get install -y jq

#
# FOR PRODUCTION, CONTROL VERSION MANUALLY
#
# install docker specific ver
# we allow held changes here in case we need to rerun, script will still work 2nd time
apt-get install -y -q docker-ce=17.09.* --allow-change-held-packages
# hold to that version
apt-mark hold docker-ce
# remove hold later for upgrade
#apt-mark unhold docker-ce
# see what upgrade options exist
#apt-cache policy docker-ce

# let the ubuntu user run docker
usermod -aG docker ubuntu

# edit dockerd startup to enable namespaces and ensure overlay2
# note namespace won't work in all scenerios, like --net=host,  
# but its tighter security so it's recommended to try using first
# this now uses the daemon.json method rather that the old way of modifying systemd
printf '{ "storage-driver" : "overlay2" }' > /etc/docker/daemon.json

if [[ -f extra_daemon_args.json ]]; then
  # back up the original
  mv /etc/docker/daemon.json /etc/docker/daemon.json.bak
  # take the original daemon file and combine it with the extra_daemon_args file
  # https://stackoverflow.com/questions/19529688/how-to-merge-2-json-file-using-jq
  jq -s '.[0] * .[1]' /etc/docker/daemon.json.bak extra_daemon_args.json > /etc/docker/daemon.json
fi

systemctl restart docker.service