#!/bin/bash

rm -f /etc/resolv.conf
echo 'nameserver 114.114.114.114' >/etc/resolv.conf

# 初始化 hostname。兼容考虑了红帽系一些老系统不是通过 /etc/hostname 来设置主机名的情况。
if [ -f /etc/hostname ]; then
    echo 'localhost' >/etc/hostname
elif [ -f /etc/sysconfig/network ]; then
    sed -i '/^HOSTNAME=/d' /etc/sysconfig/network
    echo 'HOSTNAME=localhost' >>/etc/sysconfig/network
fi

# 清理硬编码 MAC 地址信息。
[ -f /etc/udev/rules.d/70-persistent-net.rules ] && : >/etc/udev/rules.d/70-persistent-net.rules
[ -f /lib/udev/rules.d/75-persistent-net-generator.rules ] && : >/lib/udev/rules.d/75-persistent-net-generator.rules

# 清理 machine-id。
if [[ -x "$(command -v systemctl)" ]]; then
    cp --remove-destination /dev/null /etc/machine-id

    # RHEL 9 等新系统可能弃用 /var/lib/dbus/machine-id。
    if [ -f /var/lib/dbus/machine-id ]; then
        rm -f /var/lib/dbus/machine-id
        ln -s /etc/machine-id /var/lib/dbus/machine-id
    fi
elif [[ -x "$(command -v chkconfig)" ]]; then
    rm -f /etc/machine-id /var/lib/dbus/machine-id
else
    echo 'Error: Unable to determine how to initialise machine ID.'
    exit 1
fi

# 清理 cloud-init 从而重新初始化。
if ! cloud-init clean -l &>/dev/null; then
    rm -fr /var/lib/cloud/
fi

# 清空 /var/log/ 目录下的日志内容，包括但不限于 lastlog。
read -r -d '' script <<-"EOF"
import os
def clear_logs(base_path="/var/log"):
    files = os.listdir(base_path)
    for file in files:
        file_path = os.path.join(base_path, file)
        if os.path.isfile(file_path):
            with open(file_path, "w") as f:
                f.truncate()
        elif os.path.isdir(file_path):
            clear_logs(base_path=file_path)

if __name__ == "__main__":
    clear_logs()
EOF

# 获取 Python 版本来执行清理日志的脚本。
if [ -e /usr/bin/python ]; then
    python -c "$script"
elif [ -e /usr/bin/python2 ]; then
    python2 -c "$script"
elif [ -e /usr/bin/python3 ]; then
    python3 -c "$script"
else
    echo "### no python env in /usr/bin. clear_logs failed ! ###"
fi

# 其它需清理项。
rm -f /etc/ssh/ssh_host_* /var/lib/sss/db/*
rm -fr /root/*-ks.cfg /root/*.log /root/*.log.syslog /root/.bash_history /root/.cache/ /root/.pip/ \
    /root/.python_history /root/.selected_editor /root/.ssh/ /root/.wget-hsts /tmp/*.log /tmp/*.yumtx
rm -f /etc/systemd/system/startElsNic\@.service /usr/bin/start_nic.sh /usr/local/ctcloud/net/optimise/nic_set_mq.sh
rm -- "$0"
