#!/bin/sh

# Create shared directories under /persistent/shared for paths declared
# by layers in /etc/rpi-image-gen/slot-shared.d/*.conf.

set -eu

CONF_DIR=/etc/rpi-image-gen/slot-shared.d
SHARED_BASE=/persistent/shared

[ -d "$CONF_DIR" ] || exit 0

# Collect from every conf first. A StaticPath may sit under another
# conf Path, so all statics must be removed before any Path is copied.
paths=""
statics=""
for conf in "${CONF_DIR}"/*.conf; do
   [ -f "$conf" ] || continue

   version=""
   cpaths=""
   cstatics=""
   while IFS= read -r line || [ -n "$line" ]; do
       case "$line" in ''|\#*) continue ;; esac
       key="${line%%=*}"
       value="${line#*=}"
       # An empty value would resolve to the whole shared tree
       [ -n "${value#/}" ] || continue
       case "$key" in
           Version)    version="$value" ;;
           Path)       cpaths="$cpaths /${value#/}" ;;
           StaticPath) cstatics="$cstatics /${value#/}" ;;
       esac
   done < "$conf"

   if [ "$version" != "1" ]; then
       printf 'persistent-shared-init: %s: unsupported version "%s", skipping\n' \
           "$conf" "${version:-missing}" >&2
       continue
   fi

   paths="$paths$cpaths"
   statics="$statics$cstatics"
done

# Image-owned entries are replaced from the active slot by the copy below
for static in $statics; do
   printf 'persistent-shared-init: static %s\n' "$static"
   rm -rf -- "${SHARED_BASE}${static}"
done

for path in $paths; do
   printf 'persistent-shared-init: %s\n' "$path"
   mkdir -p "${SHARED_BASE}${path}"
   # Write missing files into shared, never overwriting existing ones
   [ -d "${path}" ] && rsync -av --ignore-existing "${path}/" "${SHARED_BASE}${path}/"
done
