#!/bin/sh
#EFI mount generator for ROSA Linux
#Aleksandr Kazantcev 2013
#ROSA Lab

if [ $# -gt 0 ]; then
systemd_unit_path=$1
else
systemd_unit_path=/run/systemd/generator/
fi

echo "RUN systemd EFI generator" > /dev/kmsg

#See for EFI present
if [ -d /sys/firmware/efi ]; then

# Try find EFI by gdisk CODE EF00
EFI_PART="/dev/sda$(gdisk -l /dev/sda | grep EF00 | awk '{print $1}')"
EFI_UUID=$(blkid -s PARTUUID $EFI_PART | sed 's/.*="//;s/".*//')
EFI_BY_DEV='by-partuuid'

 if [ -z $EFI_UUID ]; then
	EFI_UUID=$(blkid -s UUID $EFI_PART | sed 's/.*="//;s/".*//')
	EFI_BY_DEV='by-uuid'
 fi

#Try determine by PARTLABEL=EFI system partition and UUID
EFI_UUID=$(lsblk -Po UUID,PARTUUID,PARTLABEL,FSTYPE | grep vfat | grep 'PARTLABEL="EFI system partition"' | sed -e 's/^UUID="//;s/".*//')
EFI_BY_DEV='by-uuid'

#Try determine by PARTLABEL=EF and UUID
if [ -z $EFI_UUID ]; then
	EFI_UUID=$(lsblk -Po UUID,PARTUUID,PARTLABEL,FSTYPE | grep vfat | grep 'PARTLABEL="EF"' | sed -e 's/^UUID="//;s/".*//')
	EFI_BY_DEV='by-uuid'
fi

#Try determine by PARTLABEL=EFI system partition and PARTUUID
if [ -z $EFI_UUID ]; then
	EFI_UUID=$(lsblk -Po UUID,PARTUUID,PARTLABEL,FSTYPE | grep vfat | grep 'PARTLABEL="EFI system partition"' | sed -e 's/.*PARTUUID="//;s/".*//')
	EFI_BY_DEV='by-partuuid'
fi

#Try determine by PARTLABEL=EF and PARTUUID
if [ -z $EFI_UUID ]; then
	EFI_UUID=$(lsblk -Po UUID,PARTUUID,PARTLABEL,FSTYPE | grep vfat | grep 'PARTLABEL="EF"' | sed -e 's/.*PARTUUID="//;s/".*//')
	EFI_BY_DEV='by-partuuid'
fi

echo "EFI UUID is $EFI_UUID" > /dev/kmsg

if [ -z $EFI_UUID ]; then
    echo "Failed determine ESP UUID for $EFI_PART" > /dev/kmsg
    exit 0
fi

echo "Try write EFI partitions mount to $systemd_unit_path" > /dev/kmsg

echo "# Automatially generated by systemd-efi-boot-generator" > $systemd_unit_path/boot-efi.mount
echo "[Unit]" >> $systemd_unit_path/boot-efi.mount
echo "Description=EFI System Partition" >> $systemd_unit_path/boot-efi.mount
echo "[Mount]" >> $systemd_unit_path/boot-efi.mount
echo "Where=/boot/efi" >> $systemd_unit_path/boot-efi.mount
echo "What=/dev/disk/$EFI_BY_DEV/$EFI_UUID" >> $systemd_unit_path/boot-efi.mount
echo "Options=umask=0077,noauto" >> $systemd_unit_path/boot-efi.mount

echo "# Automatially generated by systemd-efi-boot-generator" > $systemd_unit_path/boot-efi.automount
echo "[Unit]" >> $systemd_unit_path/boot-efi.automount
echo "Description=EFI System Partition Automount" >> $systemd_unit_path/boot-efi.automount
echo "[Automount]" >> $systemd_unit_path/boot-efi.automount
echo "Where=/boot/efi" >> $systemd_unit_path/boot-efi.automount

if [ ! -d /run/systemd/generator/local-fs.target.wants ]; then
    mkdir -p /run/systemd/generator/local-fs.target.wants
fi

ln -sf $systemd_unit_path/boot-efi.automount $systemd_unit_path/local-fs.target.wants/boot-efi.automount

fi

echo "Stop write mount to EFI" > /dev/kmsg

exit 0
