#!/bin/bash
apt install debootstrap squashfs-tools sgdisk  dosfstools -y
ciqcow2=/root/debian-sid-`date +%Y-%m-%d`-cloud.qcow2
#create ciqcow2
rootdisk="/dev/nbd1"
rootfssrc="/tmp/cloudinit"
disk_setup(){
        dd if=/dev/zero of=$rootdisk bs=1M count=2048
        echo "create gpt"
        sgdisk -GZ $rootdisk >/dev/null 2>&1
        echo "create bios parttion"
        sgdisk -a1 -n1:34:2047  -t1:EF02  $rootdisk >/dev/null 2>&1
        echo "create efi parttion"
        sgdisk -a1 -n2:1M:+512M -t2:EF00 $rootdisk >/dev/null 2>&1
        echo "create root parttion"
        sgdisk -a1 -n3:513M:-4M  $rootdisk >/dev/null 2>&1
        mkfs.ext4 -F "$rootdisk"p3
        mkfs.vfat -F 32 "$rootdisk"p2
}

prepare_chroot(){
	#挂载roofs之前准备
	echo "prepare chroot"
	mount -n -t tmpfs tmpfs $rootfssrc/tmp
	mount -n -t proc /proc  $rootfssrc/proc
	mount -n -o bind /dev  $rootfssrc/dev
	mount -n -o bind /dev/pts  $rootfssrc/dev/pts
	mount -n -t sysfs sysfs $rootfssrc/sys 
	mkdir $rootfssrc/mnt/hostrun
	mount --bind /run $rootfssrc/mnt/hostrun
	chroot $rootfssrc mount --bind /mnt/hostrun /run
}
clean_chroot(){
	echo "clean chroot"
	echo clean
	umount -l $rootfssrc/proc
	umount -l $rootfssrc/sys
	umount -l $rootfssrc/dev/pts
	umount -l $rootfssrc/dev
	umount -l $rootfssrc/boot/efi/
	umount -l $rootfssrc
}


grubupdate(){
cat <<EOF >>  $rootfssrc/etc/default/grub
# Set the recordfail timeout
GRUB_RECORDFAIL_TIMEOUT=2

# Do not wait on grub prompt
GRUB_TIMEOUT=2

# Set the default commandline
GRUB_CMDLINE_LINUX_DEFAULT="console=tty1 console=ttyS0"

# Set the grub console type
GRUB_TERMINAL=console
EOF
}

create_fstab(){
e2label "$rootdisk"p3 cloudimg-rootfs
dosfslabel  "$rootdisk"p2  UEFI
cat <<EOF >  $rootfssrc/etc/fstab
LABEL=cloudimg-rootfs   /        ext4   discard,errors=remount-ro       0 1
LABEL=UEFI      /boot/efi       vfat    umask=0077      0 1
EOF
}

rm $ciqcow2
qemu-img create -f qcow2 $ciqcow2 3G
modprobe nbd
qemu-nbd -d $rootdisk
qemu-nbd -c $rootdisk $ciqcow2

disk_setup

rm /tmp/cloudinit -rf
mkdir /tmp/cloudinit
mount "$rootdisk"p3 $rootfssrc
debootstrap --no-merged-usr --no-check-gpg \
--include "ca-certificates,efibootmgr,cloud-guest-utils,linux-image-loong64,qemu-guest-agent,python3-cffi-backend,cron,iptables,isc-dhcp-client,libnss-myhostname,ntp,ntpdate,cloud-init,grub-efi,rsyslog,openssh-server,sudo,dialog,whiptail,man-db,curl,dosfstools,e2fsck-static" \
--arch=loong64 sid $rootfssrc  http://lauosc.cn:11232/debian

prepare_chroot
chroot $rootfssrc apt install -f -y
mkdir $rootfssrc/boot/efi -p
chroot $rootfssrc mount "$rootdisk"p2 /boot/efi
grubupdate
chroot $rootfssrc update-grub
chroot $rootfssrc grub-install --force
cp $rootfssrc/boot/efi/EFI/debian/grubloongarch64.efi $rootfssrc/boot/efi/EFI/debian/bootloongarch64.efi
cp -r $rootfssrc/boot/efi/EFI/debian/ $rootfssrc/boot/efi/EFI/boot/
create_fstab
rm $rootfssrc/var/cache/apt/* -rf


clean_chroot
umount $rootfssrc/boot/efi
umount $rootfssrc
qemu-nbd -d $rootdisk

