#!/bin/bash
# Build an Arch Linux ARM userdata image for Redmi Note 8 Pro (begonia) that the postmarketOS initramfs can boot.
# Layout (4096-byte sectors, MBR): p1 = ext2 "pmOS_boot", p2 = ext4 "pmOS_root"; UUIDs match the known-good boot image cmdline.
set -euo pipefail
W=${WORK:-/opt/pmos/arch-begonia}
cd "$W"
IMG=$W/arch-begonia.img
BOOT_UUID=7089ab21-41cb-4411-8c3c-f963918b6982
ROOT_UUID=3c7664bc-0afc-4799-bf9f-612eb869caa7
MNT=$W/mnt
TARBALL=$W/ArchLinuxARM-aarch64-latest.tar.gz

LO=""
cleanup() { set +e; sync; umount -R "$MNT" 2>/dev/null; [ -n "$LO" ] && losetup -d "$LO" 2>/dev/null; }
trap cleanup EXIT

echo "== create image + partitions"
rm -f "$IMG"; truncate -s 12G "$IMG"
LO=$(losetup --sector-size 4096 -Pf --show "$IMG")
echo "loop device: $LO"
printf 'label: dos\nunit: sectors\nstart=256, size=32768, type=83\nstart=33024, type=83\n' | sfdisk -q "$LO"
partprobe "$LO" 2>/dev/null || blockdev --rereadpt "$LO" || true
for i in 1 2 3 4 5 6 7 8 9 10; do [ -b "${LO}p2" ] && break; sleep 1; done
[ -b "${LO}p1" ] && [ -b "${LO}p2" ] || { echo "partition nodes missing"; exit 1; }
mkfs.ext2 -q -L pmOS_boot -U "$BOOT_UUID" "${LO}p1"
mkfs.ext4 -q -L pmOS_root -U "$ROOT_UUID" -b 4096 "${LO}p2"

echo "== mount + extract Arch Linux ARM"
mkdir -p "$MNT"; mount "${LO}p2" "$MNT"; mkdir -p "$MNT/boot"; mount "${LO}p1" "$MNT/boot"
tar -xpf "$TARBALL" -C "$MNT" --xattrs --xattrs-include='*' --numeric-owner \
    --exclude='./boot/*' --exclude='boot/*' --exclude='./usr/lib/modules/*' --exclude='usr/lib/modules/*' 2>&1 | grep -v "Ignoring unknown extended header" || true
ls "$MNT" | tr '\n' ' '; echo

echo "== kernel modules + firmware from the pmOS initramfs (matching kernel 6.16.4)"
mkdir -p "$MNT/usr/lib/modules" "$MNT/usr/lib/firmware"
cp -a "$W/initramfs/usr/lib/modules/6.16.4" "$MNT/usr/lib/modules/"
cp -a "$W/initramfs/usr/lib/firmware/." "$MNT/usr/lib/firmware/"

echo "== basic config"
cat > "$MNT/etc/fstab" <<EOF
# <file system>                          <mount point> <type> <options>             <dump> <pass>
UUID=$ROOT_UUID  /      ext4  defaults                 0 1
UUID=$BOOT_UUID  /boot  ext2  nodev,nosuid,noexec      0 2
EOF
echo begonia > "$MNT/etc/hostname"
ln -sf /usr/share/zoneinfo/Europe/Budapest "$MNT/etc/localtime"
mkdir -p "$MNT/var/log/journal"
sed -i 's/^#\?IgnorePkg.*/IgnorePkg = linux-aarch64 linux-aarch64-headers/' "$MNT/etc/pacman.conf"
grep -q '^IgnorePkg' "$MNT/etc/pacman.conf" || sed -i '/^\[options\]/a IgnorePkg = linux-aarch64 linux-aarch64-headers' "$MNT/etc/pacman.conf"

echo "== users (root + user), password from staged file, SSH keys"
PW=$(cat "$W/pw.txt")
HASH=$(openssl passwd -6 "$PW")
python3 -I - "$MNT" "$HASH" <<'PY'
import sys,re
root,h=sys.argv[1],sys.argv[2]
sh=open(f'{root}/etc/shadow').read().split('\n')
sh=[('root:'+h+':20400:0:99999:7:::') if l.startswith('root:') else l for l in sh if l and not l.startswith('user:')]
sh.append('user:'+h+':20400:0:99999:7:::'); open(f'{root}/etc/shadow','w').write('\n'.join(sh)+'\n')
pw=[l for l in open(f'{root}/etc/passwd').read().split('\n') if l and not l.startswith('user:')]
pw.append('user:x:1000:1000:user:/home/user:/bin/bash'); open(f'{root}/etc/passwd','w').write('\n'.join(pw)+'\n')
gr=[l for l in open(f'{root}/etc/group').read().split('\n') if l and not l.startswith('user:')]
gr=[(l.rstrip(':')+(',' if re.search(r':[^:]+$',l) and l.split(':')[3] else '')+'user') if l.startswith('wheel:') else l for l in gr]
gr=[l if not l.startswith('wheel:') else (l if 'user' in l.split(':')[3].split(',') else l) for l in gr]
gr.append('user:x:1000:'); open(f'{root}/etc/group','w').write('\n'.join(gr)+'\n')
PY
grep '^wheel:' "$MNT/etc/group" || true
chmod 640 "$MNT/etc/shadow" || true
mkdir -p "$MNT/home/user/.ssh" "$MNT/root/.ssh"
cp "$W/authorized_keys.txt" "$MNT/home/user/.ssh/authorized_keys"; cp "$W/authorized_keys.txt" "$MNT/root/.ssh/authorized_keys"
chmod 700 "$MNT/home/user/.ssh" "$MNT/root/.ssh"; chmod 600 "$MNT/home/user/.ssh/authorized_keys" "$MNT/root/.ssh/authorized_keys"
chown -R 1000:1000 "$MNT/home/user"; chown 0:0 "$MNT/root/.ssh" "$MNT/root/.ssh/authorized_keys"
mkdir -p "$MNT/etc/sudoers.d"; echo '%wheel ALL=(ALL:ALL) NOPASSWD: ALL' > "$MNT/etc/sudoers.d/10-wheel"; chmod 440 "$MNT/etc/sudoers.d/10-wheel"
mkdir -p "$MNT/etc/ssh/sshd_config.d"
printf 'PermitRootLogin yes\nPasswordAuthentication yes\nUsePAM yes\n' > "$MNT/etc/ssh/sshd_config.d/10-begonia.conf"

echo "== usb gadget networking + first-boot services"
mkdir -p "$MNT/usr/local/sbin" "$MNT/etc/systemd/network" "$MNT/etc/systemd/system/multi-user.target.wants"
cat > "$MNT/usr/local/sbin/usb-gadget.sh" <<'EOF'
#!/bin/sh
# USB NCM networking gadget (172.16.42.1). Skips if the initramfs already created usb0.
[ -d /sys/class/net/usb0 ] && exit 0
modprobe libcomposite 2>/dev/null || true
mountpoint -q /sys/kernel/config || mount -t configfs none /sys/kernel/config
G=/sys/kernel/config/usb_gadget/g1
mkdir -p "$G" && cd "$G" || exit 1
echo 0x18d1 > idVendor; echo 0xd001 > idProduct
mkdir -p strings/0x409; echo "Xiaomi" > strings/0x409/manufacturer; echo "Redmi Note 8 Pro (Arch Linux ARM)" > strings/0x409/product; echo begonia > strings/0x409/serialnumber
mkdir -p functions/ncm.usb0 configs/c.1/strings/0x409; echo NCM > configs/c.1/strings/0x409/configuration
ln -sf functions/ncm.usb0 configs/c.1/ 2>/dev/null
UDC=$(ls /sys/class/udc | head -n1); [ -n "$UDC" ] && echo "$UDC" > UDC
EOF
chmod 755 "$MNT/usr/local/sbin/usb-gadget.sh"
cat > "$MNT/etc/systemd/system/usb-gadget.service" <<'EOF'
[Unit]
Description=USB gadget (NCM network)
ConditionPathExists=!/sys/class/net/usb0
Before=systemd-networkd.service
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/sbin/usb-gadget.sh
[Install]
WantedBy=multi-user.target
EOF
cat > "$MNT/etc/systemd/network/20-usb0.network" <<'EOF'
[Match]
Name=usb0
[Network]
Address=172.16.42.1/24
DHCPServer=yes
[DHCPServer]
PoolOffset=2
PoolSize=10
EmitDNS=no
EmitRouter=no
EOF
# RTC/clock is unreliable on this phone: if the year is not plausible, set it from the build time
BUILD_EPOCH=$(date +%s)
cat > "$MNT/usr/local/sbin/fix-clock.sh" <<EOF
#!/bin/sh
Y=\$(date +%Y); [ "\$Y" -ge 2026 ] && [ "\$Y" -le 2040 ] && exit 0
date -s @$BUILD_EPOCH
EOF
chmod 755 "$MNT/usr/local/sbin/fix-clock.sh"
cat > "$MNT/etc/systemd/system/fix-clock.service" <<'EOF'
[Unit]
Description=Set a sane clock if the RTC is wrong
DefaultDependencies=no
Before=sysinit.target pacman-keyring-init.service systemd-timesyncd.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/fix-clock.sh
[Install]
WantedBy=sysinit.target
EOF
cat > "$MNT/etc/systemd/system/pacman-keyring-init.service" <<'EOF'
[Unit]
Description=Initialise pacman keyring (first boot)
ConditionPathExists=!/etc/pacman.d/gnupg/trustdb.gpg
After=fix-clock.service
[Service]
Type=oneshot
ExecStart=/usr/bin/pacman-key --init
ExecStart=/usr/bin/pacman-key --populate archlinuxarm
[Install]
WantedBy=multi-user.target
EOF
mkdir -p "$MNT/etc/systemd/system/sysinit.target.wants"
for u in usb-gadget pacman-keyring-init; do ln -sf /etc/systemd/system/$u.service "$MNT/etc/systemd/system/multi-user.target.wants/$u.service"; done
ln -sf /etc/systemd/system/fix-clock.service "$MNT/etc/systemd/system/sysinit.target.wants/fix-clock.service"
for u in systemd-networkd sshd; do
  [ -e "$MNT/usr/lib/systemd/system/$u.service" ] && ln -sf /usr/lib/systemd/system/$u.service "$MNT/etc/systemd/system/multi-user.target.wants/$u.service"
done
# the ALARM tarball may ship a wired DHCP network for eth*: harmless, leave it

echo "== sanity"
ls -la "$MNT/sbin/init" "$MNT/usr/lib/systemd/systemd" "$MNT/usr/bin/sshd" 2>&1 | awk "{print \$1,\$NF}" || true
ls "$MNT/usr/lib/modules"; du -sh "$MNT" | tail -1

echo "== unmount + fsck + sparse"
sync; umount "$MNT/boot"; umount "$MNT"
e2fsck -fn "${LO}p2" | tail -2; fsck.ext2 -fn "${LO}p1" | tail -1
losetup -d "$LO"; LO=""
img2simg "$IMG" "$W/arch-begonia.sparse.img"
sha256sum "$W/arch-begonia.sparse.img" > "$W/arch-begonia.sparse.img.sha256"
ls -la "$IMG" "$W/arch-begonia.sparse.img"; du -h "$W/arch-begonia.sparse.img"
shred -u "$W/pw.txt" 2>/dev/null || rm -f "$W/pw.txt"
echo BUILD_OK
