#!/bin/bash


just_installed=
if ! type -p docker; then
    echo "Installing docker..."
    type -p curl >dev/null ||
        apt-get install -y curl </dev/null

    curl -sSL https://get.docker.io | sh || exit 1
    just_installed=1
fi


if [ -n "$just_installed" ]; then
    need_restart=
    docker_version=17
    if ! [[ "$(docker --version)" == "Docker version $docker_version"* ]]; then
        version="$(apt-cache madison docker-ce |
                       cut -f 2 -d \| |
                       grep "$docker_version" |
                       head -n 1 | xargs echo)"
        ## DOWNGRADE to 17.xx because 18.xx do not support registry v1
        apt-get install -y --allow-downgrades docker-ce="$version"
        need_restart=true
    fi

    if [ -n "$need_restart" ] && [ -z "$NO_DOCKER_RESTART" ]; then
        systemctl daemon-reload &&
            service docker restart
    fi
fi