#!/bin/bash
# Ubuntu系 机器初始化
export DEBIAN_FRONTEND=noninteractive

# 函数：将子网掩码从点分十进制转换为CIDR
mask2cidr() {
    local IFS='.'
    local i
    local cidr=0
    local mask
    read -r -a mask <<< "$1"
    for i in "${mask[@]}"
    do
        case $i in
            255) let cidr+=8;;
            254) let cidr+=7;;
            252) let cidr+=6;;
            248) let cidr+=5;;
            240) let cidr+=4;;
            224) let cidr+=3;;
            192) let cidr+=2;;
            128) let cidr+=1;;
            0);;
            *) echo "Error: $i is not recognized"; exit 2;;
        esac
    done
    echo $cidr
}

Get_Network_Info() {
    # 获取所有当前分配了IP的物理网卡名（排除lo和类似的虚拟接口）
    interfaces=`ip addr | awk '/^[0-9]+:/ {gsub(/:/,"",$2); print $2}' | grep -v '^lo'`

    # 初始化 INTERFACE 和 My_MAC 变量
    INTERFACE=""
    My_MAC=""

    # 循环处理每个物理网卡
    for interface in $interfaces; do
        # 使用 ethtool 命令检查网卡链接状态
        link_status=$(ethtool $interface | awk '/Link detected:/ {print $3}')
      
        # 如果链接状态为 yes，则获取 MAC 地址
        if [[ $link_status == yes ]]; then
            mac_address=$(ethtool -P $interface | awk '{print $3}')
            INTERFACE="$interface"
            My_MAC=$(echo $mac_address | sed 's/:/-/g')
            break  # 找到一个就退出循环
        fi
    done
}

Get_Sysinfo() {
    PXE_Domain="pxes.com"
    Server_Info_Url="http://${PXE_Domain}/api/01-${My_MAC}"
    Server_Json=$(curl -s "$Server_Info_Url")
    server_ip=`echo $Server_Json | grep -Po 'server_ip[" :]+\K[^"]+'`
    netmask=`echo $Server_Json | grep -Po 'netmask[" :]+\K[^"]+'`
    CIDR=$(mask2cidr $netmask)
    gateway=`echo $Server_Json | grep -Po 'gateway[" :]+\K[^"]+'`
    dns1=`echo $Server_Json | sed 's/\[/\n/g' |sed 's/\]/ /g' | sed 's/,/\n/g' | grep -A2 dns | egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | sed -n '1p'`
    dns2=`echo $Server_Json | sed 's/\[/\n/g' |sed 's/\]/ /g' | sed 's/,/\n/g' | grep -A2 dns | egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | sed -n '2p'`
    root_passwd=`echo $Server_Json | grep -Po 'l_password[" :]+\K[^"]+'`
    root_login_port=`echo $Server_Json | grep -Po 'l_port[" :]+\K[^"]+'`
}

Change_Network() {
    IP_CIDR="$server_ip/$CIDR"    
    # 创建Netplan配置文件
    CONFIG_PATH="/etc/netplan/01-netcfg.yaml"
    cat <<EOF | sudo tee $CONFIG_PATH > /dev/null
network:
  version: 2
  ethernets:
    $INTERFACE:
      dhcp4: no
      addresses:
        - $IP_CIDR
      routes:
        - to: default
          via: $gateway
      nameservers:
        addresses:
          - $dns1
          - $dns2
EOF
        
    echo "Applying configuration..."
    sudo chmod 600 $CONFIG_PATH
    sudo netplan apply
    echo "Network configuration applied successfully."    
    cat <<EOF | sudo tee /etc/resolv.conf > /dev/null
nameserver $dns1
nameserver $dns2
EOF
}

Modify_Root() {
    echo root:${root_passwd}|sudo chpasswd
    #sed -i '/^#Port 22/a\Port \$root_login_port' /etc/ssh/sshd_config
    sudo sed -i '/^#PermitRootLogin/a\PermitRootLogin yes' /etc/ssh/sshd_config
    sudo sed -i '/^#GSSAPIAuthentication/a\GSSAPIAuthentication no' /etc/ssh/sshd_config
    sudo systemctl restart sshd
}

Disable_IPV6() {
  echo "net.ipv6.conf.all.disable_ipv6 = 1" | sudo tee -a /etc/sysctl.conf
  echo "net.ipv6.conf.default.disable_ipv6 = 1" | sudo tee -a /etc/sysctl.conf
  echo "net.ipv6.conf.lo.disable_ipv6 = 1" | sudo tee -a /etc/sysctl.conf

  sudo sysctl -p

  sudo sed -i 's/^GRUB_CMDLINE_LINUX_DEFAULT=.*/GRUB_CMDLINE_LINUX_DEFAULT="ipv6.disable=1"/' /etc/default/grub
  sudo sed -i 's/^GRUB_CMDLINE_LINUX=.*/GRUB_CMDLINE_LINUX="ipv6.disable=1"/' /etc/default/grub
  sudo update-grub
}

RemoveAutoInstallProxy() {
  echo "" > /etc/apt/apt.conf.d/90curtin-aptproxy
  userdel -r ubuntu
}

RemoveLoginInfo() {
  sudo mkdir -p /etc/update-motd.d/bak
  sudo mv /etc/update-motd.d/* /etc/update-motd.d/bak
  sudo echo "Welcome Use 59Dun Netowrk Server" > /etc/update-motd.d/00-my-welcome-info  
  sudo echo "" > /etc/legal
  sudo sed -i '/^PrintMotd/s/.*/PrintMotd yes/' /etc/ssh/sshd_config
}

Get_Network_Info
Get_Sysinfo
#curl -l -H "Content-type: application/json" -X POST -d '{"mac_addr":"01-'${My_MAC}'","status":"6"}' http://pxes.com/status
curl -l -H "Content-type: application/json" -X POST -d '{"mac_addr":"01-'${My_MAC}'","status":"0"}' http://pxes.com/status
Change_Network
sudo rm -rf /etc/netplan/50-cloud-init.yaml
Modify_Root
#curl -l -H "Content-type: application/json" -X POST -d '{"mac_addr":"01-'${My_MAC}'","status":"0"}' http://pxes.com/status
hostnamectl set-hostname ubuntu
RemoveLoginInfo
#Disable_IPV6
RemoveAutoInstallProxy
sudo touch /etc/cloud/cloud-init.disabled
reboot
