#!/bin/bash
echo "====安装QEMU、libvirt、virt-manager..."
apt update -y
apt install qemu-kvm libvirt-daemon-system libvirt-clients bridge-utils -y
apt install virt-manager -y

apt install pv -y

apt install net-tools -y

echo "====创建文件夹..."
mkdir /data/vms1 -p
mkdir /data/vms2 -p
mkdir /data/imgs -p
mkdir /data/cloud-init-templates -p

# 下载镜像
echo "====下载镜像..."
wget -O /data/imgs/jammy-server-cloudimg-amd64.img http://104.37.175.72/jammy-server-cloudimg-amd64.img

# 配置网络
echo "====写入network-config.yaml..."
cat << ENOF > /data/cloud-init-templates/network-config.yaml
# 配置网络
network:
  version: 2
  ethernets:
    enp1s0:
      addresses: [{{.Ipv4}}/{{.Netmask}}]
      gateway4: {{.Gateway}}
      nameservers:
        addresses: [8.8.8.8, 8.8.4.4]
ENOF

# 配置cloud-nint
echo "====写入cloud-init.yaml..."
cat << ENOF > /data/cloud-init-templates/cloud-init.yaml
#cloud-config

# 设置主机名
hostname: {{.Hostname}}

ssh_pwauth: true
password: {{.InitPassword}}
chpasswd:
  expire: false

disable_root: false
disable_root_opts: ""

runcmd:
  - echo {{.MachineId}} > /etc/machine-id
ENOF

echo "====Virsh Agent 安装&启动..."
wget -O /bin/virsh_agent http://104.37.175.72/virsh_agent
chmod +x /bin/virsh_agent
/bin/virsh_agent --daemon

# 配置网桥
echo "====写入br0.yaml 配置网桥..."
read -p "请输入网桥 IP 地址,格式:10.10.110.1/25: " br0_Ipv4
cat << ENOF > /etc/netplan/br0.yaml
network:
  version: 2
  renderer: networkd
  bridges:
    br0:            # 网桥的名称
      addresses: [$br0_Ipv4] # 网桥 IP 地址，可以留空
      mtu: 1500
      dhcp4: no    # 启用 DHCPv4
      dhcp6: no    # 禁用 DHCPv6
ENOF

# 应用网桥配置
netplan apply

# 编辑 /etc/sysctl.conf 文件以启用 IP 转发
# 使用 echo 命令追加文本到文件中，如果文件中已经存在该行则不重复添加
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf

# 使用 sysctl -p 应用 /etc/sysctl.conf 中的更改
sysctl -p

rm -rf ./init.sh
echo "系统环境初始化完成！"