#!/usr/bin/env bash

# Install docker
set -x
# echo "deb http://apt.dockerproject.org/repo debian-stretch main" >> /etc/apt/sources.list.d/docker.list

ARCH=$(dpkg --print-architecture)

TYPES=(deb)
TRANSPORT="https:/"
URI=download.docker.com
SUITES=trixie
COMPONENTS=stable
ARCHITECTURES=(amd64)
#KEY_DIR=/etc/apt/trusted.gpg.d
KEY_DIR=/usr/share/keyrings
KEY=${KEY_DIR}/docker.gpg
sudo mkdir -p ${KEY_DIR}
KEY_URL="${TRANSPORT}/${URI}/linux/debian/gpg"
sudo curl -fsSL ${KEY_URL} | sudo gpg --dearmor -o ${KEY}
sudo chmod a+r ${KEY}

mkdir -p /etc/apt/sources.list-available
#cat <<-EOF | sudo tee /etc/apt/sources.list-available/docker.list
#	deb [arch=${ARCH} signed-by=${KEY}] ${TRANSPORT}/${URI}/linux/debian ${VERSION_CODENAME} stable
#EOF

conf_print_docker_sources() {
  cat <<EOF
Enabled: yes
Types: ${TYPES[*]}
URIs: ${TRANSPORT}/${URI}/linux/debian
Suites: ${SUITES}
Components: ${COMPONENTS[*]}
Architectures: ${ARCHITECTURES[*]}
Signed-By: ${KEY}
EOF
}
conf_print_docker_sources | sudo tee /etc/apt/sources.list-available/docker.sources

sudo ln -sf /etc/apt/sources.list-available/docker.sources /etc/apt/sources.list.d/docker.sources

# Bypass apt-proxy for docker packages
if [ -f /etc/apt/apt.conf.d/02proxy ]; then
  if [ ! -z "$(grep "${TRANSPORT}/${URI}" /etc/apt/apt.conf.d/02proxy)" ]; then
    echo "Acquire::http::Proxy { \"${TRANSPORT}/${URI}\" DIRECT; };" | sudo tee /etc/apt/apt.conf.d/02proxy
  fi
fi

# apt update
sudo apt install -y --force-yes jq
sudo apt remove "$(dpkg --get-selections docker.io docker-compose docker-compose-v2 docker-doc podman-docker containerd runc | cut -f1)"
sudo apt install -y \
  apt-transport-https \
  ca-certificates \
  curl \
  pass \
  gnupg2
#  software-properties-common

sudo apt install -y \
  docker-ce \
  docker-ce-cli \
  containerd.io \
  docker-compose-plugin \
  docker-buildx-plugin \
  python3-docker \
  python3-compose
# docker-ce-rootless-extras \

# docker scout

# apt install -y --force-yes docker-engine=1.9.1-0~jessie

# mkdir -p /var/lib/docker
# umount /dev/mapper/vg_prime-varLibDockerLV
# mount /dev/mapper/vg_prime-varLibDockerLV /var/lib/docker

## /etc/default/docker
## NB. We use the /etc/docker/daemon.json instead of this file. Options cannot be set in both.
# bash -c 'perl -p -i -e "s/#DOCKER_RUN_OPTS=\"\"/DOCKER_RUN_OPTS=\"--restart=true\"/g"  /etc/default/docker'
# bash -c 'sed -i "s|DOCKER_RUN_OPTS=\"\(.*\)\"|DOCKER_RUN_OPTS=\"\1 --storage-driver=zfs\"|" /etc/default/docker'
# bash -c 'sed -i "s|DOCKER_RUN_OPTS=\"\(.*\)\"|DOCKER_RUN_OPTS=\"\1 --dns 52.174.55.168 --dns 188.165.200.156\"|" /etc/default/docker'
# bash -c 'sed -i "s|DOCKER_RUN_OPTS=\"\(.*\)\"|DOCKER_RUN_OPTS=\"\1 zfs.fsname=rpool/docker\"|" /etc/default/docker'
# bash -c " sed -i '/^DOCKER_RUN.*/    s/^/#/' /etc/default/docker"

# enable experimental features - done in /etc/docker/daemon.json below.
# bash -c 'sed -i "/^# Docker Upstart.*/ s/.*/&\nDOCKER_CLI_EXPERIMENTAL=enabled/" /etc/default/docker'
# bash -c " sed -i '/^DOCKER_CLI_EXPERIMENTAL=.*/    s/^/#/' /etc/default/docker"

# enable buildkit builds - done in /etc/docker/daemon.json below.
# bash -c 'sed -i "/^# Docker Upstart.*/ s/.*/&\nDOCKER_BUILDKIT=1/" /etc/default/docker'
# bash -c " sed -i '/^DOCKER_BUILDKIT.*/    s/^/#/' /etc/default/docker"

# i2p container requires ipv6  - done in /etc/docker/daemon.json below.
#bash -c 'sed -i "s|DOCKER_RUN_OPTS=\"\(.*\)\"|DOCKER_RUN_OPTS=\"\1 --ipv6\"|" /etc/default/docker'

# The above can also be passed in /etc/docker/daemon.json
# For other options:
# http://github.com/moby/moby/pull/23657/files?short_path=ca4f406
# https://gist.github.com/lvdh/1f2d50ad49274413d3e501b71a59e819
mkdir -p /etc/docker
if [ ! -f /etc/docker/daemon.json ]; then
  touch /etc/docker/daemon.json
  echo "{}" >/etc/docker/daemon.json
else
  echo "/etc/docker/daemon.json exists."
fi

## Default configuration file on linux:
## /etc/docker/daemon.json

# DOCKER_RUN_OPTS="
#	--storage-driver=zfs
#	--dns 52.174.55.168
#	--dns 188.165.200.156
#	zfs.fsname=rpool/docker
#	--ipv6"

# Note: You cannot set options in daemon.json that have already been set on daemon startup as
# a flag in /etc/default/docker the docker daemon will refuse to start.
#
## This is a full example of the allowed configuration options on Linux:
## https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-configuration-file
## See /var/tmp/automate/docker_daemon-writer.sh for complete jq example.

# NB live-restore is incompatible with swarm mode.

declare -A DOCKER_OPT

DOCKER_OPT[0]='.["dns"] = ["1.1.1.1","1.0.0.1"]'
DOCKER_OPT[1]='.["live-restore"] = true'
DOCKER_OPT[2]='.["storage-driver"] = "zfs"'
DOCKER_OPT[3]='.["storage-opts"] = ["zfs.fsname=rpool/docker"]'
DOCKER_OPT[4]='.["ipv6"] = false'
DOCKER_OPT[5]='.["insecure-registries"] = ["soleine.lan:5000"]'
DOCKER_OPT[6]='.["features"] = {"buildkit": true}'
DOCKER_OPT[7]='.["exec-opts"] = ["native.cgroupdriver=cgroupfs"]' # if omitted docker defaults to cgroupfs v1 and docker exec will fail, /etc/rc.conf rc_cgroup_mode="unified"
DOCKER_OPT[8]='.["registry-mirrors"] = ["https://git2.ring-zero.co.uk", "https://mirror.gcr.io"]'
DOCKER_OPT[9]='.["log-driver"] = "json-file"'
DOCKER_OPT[10]='.["log-opts"] = {"max-size": "10m", "max-file": "3"}'
#DOCKER_OPT[11]='.["hosts"] = ["fd://","unix:///var/run/docker.sock","tcp://0.0.0.0:2376"]'
#DOCKER_OPT[12]='.["experimental"] = true'o

# Change /etc/rc.conf to set cgroup v2
sed -i '/^#rc_cgroup_mode=.*/ s/.*/&\nrc_cgroup_mode=\"unified\"/' /etc/rc.conf

for ((i = 0; i < ${#DOCKER_OPT[@]}; ++i)); do
  OPTION="${DOCKER_OPT[$i]}"
  jq "${OPTION}" /etc/docker/daemon.json >/tmp/daemon.json.new &&
    sudo mv -b /tmp/daemon.json.new /etc/docker/daemon.json
done

# General options
## Adding a personal registry.
#DOCKER_OPT[0]='.["insecure-registries"] = ["mydocker-registry.net:5000"]'
## Allow live restore, keep containers alive when the daemon becomes unavailable.
## Not compatible with swarm mode.
#DOCKER_OPT[1]='.["live-restore"] = ["true"]'
## Debugging on
#DOCKER_OPT[2]='.["debug"] = ["true"]'
## IPv6 for i2p container
#DOCKER_OPT[3]='.["ipv6"] = ["true"]'
## Logging options
#DOCKER_OPT[4]='.["log-driver"] = ["syslog"]'
##DOCKER_OPT[4]='.["log-opts"] = ["syslog-address","udp://1.2.3.4:1111"]'
#
#for ((i = 0; i < ${#DOCKER_OPT[@]}; ++i)); do
#	OPTION="${DOCKER_OPT[$i]}"
#	jq "${OPTION}" /etc/docker/daemon.json > /tmp/daemon.json.new && \
#		mv -b /tmp/daemon.json.new /etc/docker/daemon.json
#done

## Use TLS (HTTPS) to protect the Docker daemon socket instead of SSH
# This is something we usually do with letsencrypt
# https://docs.docker.com/engine/security/protect-access/
# Should be on the same dataset as the docker rpool (/var/lib/docker)
# TLS_HOME="/var/lib/docker/certs.d"
# KEYNAME="server"
# TLSHOSTS="tcp://192.168.59.3:2376"
#
# mkdir -p ${TLS_HOME}
#{
#  "debug": true,
#  "tls": true,
#  "tlscert": "/var/docker/server.pem",
#  "tlskey": "/var/docker/serverkey.pem",
#  "hosts": ["tcp://192.168.59.3:2376"]
#}
#DOCKER_OPT[9]='.["tls"] = true'
#DOCKER_OPT[10]=".["tlscert"] = "${TLS_HOME}/${KEYNAME}.pem""
#DOCKER_OPT[11]=".["tlskey"] = "${TLS_HOME}/${KEYNAME}key.pem""
#DOCKER_OPT[12]=".["hosts"] = ["${TLSHOSTS}"]"

# Replace all instances of $HOST in the following with the DNS name of your
# Docker daemon’s host.

## Change the subj line to reflect your details for key generation and uncomment
## above to turn tls on.
#openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 \
#	-subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=${HOST}" \
#	-keyout ${TLS_HOME}/${KEYNAME}_key.pem \
#	-out ${TLS_HOME}/${KEYNAME}.pem

# Add tls - we keep the keys on the docker zfs dataset not /etc/docker/tls
#DOCKER_OPT[0]='.["tls"] = ["true"]'
#DOCKER_OPT[1]='.["tlscacert"] = ["${TLS_HOME}/ca.pem"]'
#DOCKER_OPT[2]='.["tlscert"] = ["${TLS_HOME}/${KEYNAME}.pem"]'
#DOCKER_OPT[3]='.["tlskey"] = ["${TLS_HOME}/${KEYNAME}_key.pem"]'
#DOCKER_OPT[4]='.["tlsverify"] = ["true"]'
#DOCKER_OPT[5]='.["hosts"] = ["tcp://192.168.59.3:2376"]'

#for ((i = 0; i < ${#DOCKER_OPT[@]}; ++i)); do
#	OPTION="${DOCKER_OPT[$i]}"
#	jq "${OPTION}" /etc/docker/daemon.json > /tmp/daemon.json.new && \
#		mv -b /tmp/daemon.json.new /etc/docker/daemon.json
#done

## Something similar to set up a swarm
#DOCKER_OPT[0]='.["cluster-advertise"] = "192.168.1.116:12376"'
#DOCKER_OPT[1]='.["cluster-store"] = "etcd://192.168.1.116:12379"'
#DOCKER_OPT[2]='.["cluster-store-opts"] = { "kv.cacertfile" : "/var/lib/docker/discovery_certs/ca.pem", "kv.certfile" : "/var/lib/docker/discovery_certs/cert.pem", "kv.keyfile" : "/var/lib/docker/discovery_certs/key.pem" }'
#for ((i = 0; i < ${#DOCKER_OPT[@]}; ++i)); do
#	OPTION="${DOCKER_OPT[$i]}"
#	jq "${OPTION}" /etc/docker/daemon.json > /tmp/daemon.json.new && \
#		mv -b /tmp/daemon.json.new /etc/docker/daemon.json
#done

#groupadd docker
#usermod -aG docker $USER
#gpasswd -a "$USER_NAME" docker
#newgrp docker

#/etc/init.d/docker restart
