config() {
  NEW="$1"
  OLD="$(dirname $NEW)/$(basename $NEW .new)"
  # If there's no config file by that name, mv it over:
  if [ ! -r $OLD ]; then
    mv $NEW $OLD
  elif [ "$(cat $OLD | md5sum)" = "$(cat $NEW | md5sum)" ]; then
    # toss the redundant copy
    rm $NEW
  fi
  # Otherwise, we leave the .new copy for the admin to consider...
}

preserve_perms() {
  NEW="$1"
  OLD="$(dirname $NEW)/$(basename $NEW .new)"
  if [ -e $OLD ]; then
    cp -a $OLD ${NEW}.incoming
    cat $NEW > ${NEW}.incoming
    mv ${NEW}.incoming $NEW
  fi
  config $NEW
}

preserve_perms etc/rc.d/rc.docker.new
config etc/default/docker.new
config etc/logrotate.d/docker.new

# Reload udev rules, we just added one with this package:
if [ -x /sbin/udevadm ]; then
  /sbin/udevadm control --reload-rules
fi

# Group 'docker' (grpId=281) is also used by SBo.
DOCKER_GID=${DOCKER_GID:-281}

# Only way to create and use the correct uid and gid on the target system,
# is to use chroot:
chroot . <<EOR 2>/dev/null
# Add the '${DOCKER_GID}' group if it doesn't exist already:
/usr/sbin/groupadd -g ${DOCKER_GID} docker 2> /dev/null
EOR

# Update rc.local so that docker daemon will be started on boot:
if ! grep "rc.docker" etc/rc.d/rc.local 1>/dev/null 2>&1 ; then
  cat <<_EOM_ >> etc/rc.d/rc.local

if [ -x /etc/rc.d/rc.docker ]; then
  # Start Docker daemon:
  echo "Starting Docker daemon:    /etc/rc.d/rc.docker start"
  /etc/rc.d/rc.docker start
fi
_EOM_
fi

# Update rc.local_shutdown so that docker daemon will be stopped:
if ! grep "rc.docker" etc/rc.d/rc.local_shutdown 1>/dev/null 2>&1 ; then
  cat <<_EOM2_ >> etc/rc.d/rc.local_shutdown

if [ -x /etc/rc.d/rc.docker ]; then
  # Stop Docker daemon:
  echo "Stopping Docker daemon:    /etc/rc.d/rc.docker stop"
  /etc/rc.d/rc.docker stop
fi
_EOM2_
fi

( cd usr/bin ; rm -rf docker-buildx )
( cd usr/bin ; ln -sf /usr/lib/docker/cli-plugins/docker-buildx docker-buildx )
