#!/bin/bash

# This script will clean the rootfs for a normal usage.
# Globally, it will cancel effects of the builder-enter script.
# It also clean rootfs to make image "forkable"

set -e

# unprevent init scripts from running during install/update
lsb_dist="$(lsb_release -si 2>/dev/null || (test -f /etc/lsb-release && . /etc/lsb-release; echo ${DISTRIB_ID:-no_lsb}))"
lsb_release="$(lsb_release -sr 2>/dev/null || (test -f /etc/lsb-release && . /etc/lsb-release; echo ${DISTRIB_RELEASE:-no_lsb}))"

case "$lsb_dist" in
    Ubuntu)
        dpkg-divert --remove /sbin/initctl
        rm -f /usr/sbin/policy-rc.d /sbin/initctl /sbin/initctl.distrib
        mv /sbin/initctl.orig /sbin/initctl
        chmod 755 /sbin/initctl
        ;;
    Debian)
        dpkg-divert --remove /sbin/initctl
        rm -f /usr/sbin/policy-rc.d /sbin/initctl /sbin/initctl.distrib
        ;;
    *)
        echo "Warning: unsupported distribution $lsb_dist ($lsb_release)" >&2
        ;;
esac


# remove potentially existing docker aptitude tuning
rm -f /etc/apt/apt.conf.d/docker-*
#rm -f /.dockerenv /.dockerinit

# remove ssh host keys so they are regenerated on first boot
rm -f /etc/ssh/*_key*

# clean history
rm -f /root/.history /root/.bash_history

# clean aptitude
rm -f /var/cache/apt/*.bin /var/cache/apt/archives/partial/*.deb \
      /var/cache/apt/archives/*.deb

# clean debootstrap
rm -f /var/log/bootstrap.log

# clean systemd
rm -f /var/log/journal/*

# Update locate cache
updatedb 2>/dev/null || true
