#!/bin/bash

set -eu -o pipefail
set -x

SYNC_COMMAND="/usr/libexec/efimirror/efimirror-sync"

# shellcheck source=functions.sh.in
source "/usr/libexec/efimirror/functions.sh"

# shellcheck source=/dev/null
source "$EFIMIRROR_CONFIG_PATH"

test -v MOUNT_OPTS
test -v MOUNT_BASE

generator_dir="$1"
early_generator_dir="$2"

declare -a efi_partitions
if ! get_efi_partitions efi_partitions; then
  print "Error: no EFI partitions found, exiting"
  exit 1
fi

cur_efi_partuuid=$(get_primary_efi_partition efi_partitions)

mkdir -p "${generator_dir}/local-fs.target.requires"

mount_unit_prefix=$(systemd-escape --path "$MOUNT_BASE")

cat > "${generator_dir}/efimirror@.service" <<EOF
[Unit]
BindsTo=${mount_unit_prefix}-%i.mount
After=${mount_unit_prefix}-%i.mount
Requires=boot-efi.mount
After=boot-efi.mount
RefuseManualStart=true
RefuseManualStop=true

[Service]
Type=simple
ExecStart=$SYNC_COMMAND sync ${MOUNT_BASE}/%I
ExecStop=$SYNC_COMMAND shutdown ${MOUNT_BASE}/%I

ProtectSystem=strict
ReadWritePaths=${MOUNT_BASE}/%I
ProtectHome=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectControlGroups=yes
PrivateTmp=yes
PrivateMounts=yes
NoNewPrivileges=yes
AmbientCapabilities=
CapabilityBoundingSet=CAP_CHOWN,CAP_SETFID
EOF

boot_efi_unit_name=$(systemd-escape --path "/boot/efi")

for partuuid in "${efi_partitions[@]}"; do
  mount_path="${MOUNT_BASE}/${partuuid}"
  mount_unit_name=$(systemd-escape --path "$mount_path")

  dev_path="/dev/disk/by-partuuid/${partuuid}"

  partuuid_unit_name=$(systemd-escape "$partuuid")

  (cd "$generator_dir/local-fs.target.requires"; ln -s "../${mount_unit_name}.mount" .)

  if [[ "$partuuid" == "$cur_efi_partuuid" ]]; then
    cat > "${early_generator_dir}/${boot_efi_unit_name}.mount" <<EOF
[Mount]
What=$mount_path
Where=/boot/efi
Type=none
Options=bind
EOF
  else
    cat > "${generator_dir}/${mount_unit_name}.mount" <<EOF
[Unit]
Upholds=efimirror@${partuuid_unit_name}.service
EOF
  fi
  cat >> "${generator_dir}/${mount_unit_name}.mount" <<EOF
[Mount]
What=$dev_path
Where=$mount_path
Type=vfat
Options=$MOUNT_OPTS
EOF
done

(cd "$generator_dir/local-fs.target.requires"; ln -s "../${boot_efi_unit_name}.mount" .)
