raspi-flash/provision-pi.sh

107 lines
2.1 KiB
Bash
Executable file

#!/usr/bin/env bash
# SPDX-FileCopyrightText: 2026 Laborratte5 laborratte5@gmail.com
# SPDX-License-Identifier: GPL-3.0-only
flash_sd () {
img_file=$1
sd_card=$2
echo "Flashing $img_file to $sd_card ..."
xzcat --stdout $img_file | dd of=$sd_card status=progress
}
enlarge_partition () {
device=$1
partnr=2
echo "Resize main partition"
sfdisk --backup $device -N $partnr << EOF
,+
print
EOF
echo "Resize filesystem"
e2fsck -f "$device"p$partnr
resize2fs -p "$device"p$partnr
}
mount_temporary () {
partnr=$1
temp_mnt_point=$(mktemp -d)
mount "$SD_CARD"p"$partnr" $temp_mnt_point
echo $temp_mnt_point
}
unmount_temporary () {
handle=$1
umount $1
rmdir $1
}
provision_network () {
mnt_point=$1
echo "Provision network"
cat > $mnt_handle/network-config <<EOF
network:
version: 2
ethernets:
eth0:
addresses: [$NET_ADDR]
routes:
- to: default
via: $DEFAULT_GATEWAY
EOF
}
provision_user () {
mnt_point=$1
echo "Provision user"
if [ -f $ssh_key ]; then
# Load key from file
echo "Loading ssh key from file $ssh_key"
ssh_key=$(<$ssh_key)
fi
cat > $mnt_point/user-data <<EOF
#cloud-config
hostname: raspberry-pi
manage_etc_hosts: true
timezone: Europe/Berlin
package_update: true
package_upgrade: true
enable_ssh: true
users:
- name: $username
group: users,adm,dialout,audio,netdev,video,plugdev,cdrom,games,input,gpio,spi,i2c,render,sudo
shell: /bin/bash
lock_passwd: false
plain_text_passwd: $userpw
sudo: ALL=(ALL) ALL
ssh_authorized_keys:
- $ssh_key
EOF
}
read -e -p "Compressed Image file: " IMG_FILE
read -e -p "SD Card: " SD_CARD
read -e -p "IP-Address with prefix (comma separated): " NET_ADDR
read -e -p "Default Gateway: " DEFAULT_GATEWAY
read -e -p "Username: " username
read -s -p "Password: " userpw
echo
read -e -p "SSH-Key: " ssh_key
echo
flash_sd "$IMG_FILE" "$SD_CARD"
enlarge_partition "$SD_CARD"
mnt_handle=$(mount_temporary "1")
provision_network $mnt_handle
provision_user $mnt_handle
unmount_temporary $mnt_handle