#!/bin/bash

set -e

source /opt/datadog/apm/inject/common_functions.sh

daemon_config="/etc/docker/daemon.json"
daemon_config_backup="/etc/docker/daemon.json.bak"

function usage ()
{
    cat << EOF
Datadog Container Injection Support Installer
Usage :  $0 [options]

    Options:
    -h|--help             OPTIONAL Display this message
    --uninstall           OPTIONAL Remove installation
    --no-config-change    OPTIONAL Do not alter daemon.json
    --no-docker-reload    OPTIONAL Do not reload docker config
EOF

}

# to do:
# on install:
# create the create the directory that hosts the UDS and set the permissions on it correctly (chown root:root chmod 777)
# copy the new daemon.json file (which configured docker to use the runc shim) into place and back up any existing one.
#
# on uninstall:
# remove the daemon.json file and replace it with the backup.

if [ -z "$uninstall_flag" ]; then
  $sudo_cmd sh -c "mkdir -p /opt/datadog/apm/inject/run"
  $sudo_cmd sh -c "chown -R root:root /opt/datadog/apm/inject/run"
  $sudo_cmd sh -c "chmod -R 777 /opt/datadog/apm/inject/run"

  # Do nothing if --no-config-change or we detect dd-shim in the daemon config
  if [ -z "$no_config_change" ] && { [ ! -f $daemon_config ] || ! grep -q dd-shim $daemon_config; }; then
    # Backup old docker daemon config
    if [ -f "$daemon_config" ] ; then
      $sudo_cmd sh -c "mv $daemon_config $daemon_config_backup"
      echo "Backed up $daemon_config to $daemon_config_backup"
    fi

    # Link new daemon config
    $sudo_cmd sh -c "ln -s $BINARY_INSTALL_PATH/daemon.json /etc/docker/daemon.json"
    echo "Linked docker daemon.json config"
  fi

else
  if [ -z "$no_config_change" ]; then
    # Delete daemon config if it contains "dd-shim"
    if [ -f $daemon_config ] && grep -q dd-shim $daemon_config; then
      $sudo_cmd sh -c "rm $daemon_config"
      echo "Removed $daemon_config"
    fi

    # Restore backup if it doesn't overwrite
    if [ -f "$daemon_config_backup" ] && [ ! -f $daemon_config ] ; then
      $sudo_cmd sh -c "mv $daemon_config_backup $daemon_config"
      echo "Restored $daemon_config_backup to $daemon_config"
    fi
  fi
fi

# Reload happens in both the install and uninstall case
if [ -z "$no_docker_reload" ]; then
  service_control reload docker
fi
