#!/bin/sh

clean_files() {
        rm -f /etc/ssh/*key*
        sed -r -i '/sh \/dev\/sda/d' /etc/rc.local
}

disk_format() {
    fdisk /dev/vda <<EOF
d
2
n
p
2


w
EOF
}

resize_fs() {
    cat > /etc/systemd/system/resize_fs.service <<'EOF'
[Unit]
Description=Resize Filesystem
Requires=systemd-fsck@dev-vda2.service
After=systemd-fsck@dev-vda2.service local-fs.target

[Service]
Type=oneshot
ExecStart=/usr/sbin/resize2fs -p /dev/vda2

[Install]
WantedBy=multi-user.target
EOF

    chmod +x /etc/systemd/system/resize_fs.service
    systemctl enable resize_fs.service
    systemctl start resize_fs.service
}


network_configure() {
    IPv4=($IPv4)
    NETMASKv4=($NETMASKv4)
    GATEWAYv4=($GATEWAYv4)
    IPv6=($IPv6)
    NETMASKv6=($NETMASKv6)
    GATEWAYv6=($GATEWAYv6)
    HOSTNAME=($HOSTNAME)
    NAMESERVER=($NAMESERVER)

    if [ -n "${GATEWAYv4}" ]; then
        GATEWAY=${GATEWAYv4}
    else
        GATEWAY=${GATEWAYv6}
    fi

    # Removing udev rules
    rm -f /etc/udev/rules.d/70-persistent-net.rules

    # Configuring network
    sed -r -i '/^HOSTNAME=/d; /^GATEWAY=/d' /etc/sysconfig/network
    cat >> /etc/sysconfig/network << EOF
HOSTNAME=${HOSTNAME}
GATEWAY=${GATEWAY}
EOF

    MAC_ADDR=$(ip link show ens3 | awk '/link\/ether/ {print $2}')

    cat > /etc/sysconfig/network-scripts/ifcfg-ens3 << EOF
DEVICE="ens3"
BOOTPROTO="static"
DNS1="${NAMESERVER}"
HWADDR="${MAC_ADDR}"
NM_CONTROLLED="yes"
ONBOOT="yes"
TYPE="Ethernet"
EOF

    if [ -n "${IPv4}" ]; then
        cat >> /etc/sysconfig/network-scripts/ifcfg-ens3 << EOF
IPADDR="${IPv4}"
NETMASK="${NETMASKv4}"
GATEWAY="${GATEWAYv4}"
EOF
    else
        cat >> /etc/sysconfig/network-scripts/ifcfg-ens3 << EOF
IPV6INIT="yes"
IPV6ADDR="${IPv6}/${NETMASKv6}"
IPV6_DEFAULTGW="${GATEWAYv6}"
EOF
    fi

    systemctl restart network
}

# Очистка истории команд
unset HISTFILE
history -c

clean_files
disk_format
resize_fs
echo "($PASS)" | passwd --stdin root
network_configure
wget -q -O /dev/null --no-check-certificate "($FINISH)"
reboot