#!/bin/sh
set -e

create=0
root=''
confs=''

for arg; do
  case "${arg}" in
    --create)  create=1 ;;
    --root=*)  root="${arg#--root=}" ;;
    --*)       ;;
    *)         confs="${confs} ${arg}" ;;   # Support multiple .conf form debhelper: $ systemd-tmpfiles --create foo.conf bar.conf
  esac
done

[ "${create}" = 1 ] && [ -n "${confs}" ] || exit 0

## Deliberate word-splitting for multiple .confs
# shellcheck disable=SC2086
for conf in ${confs}; do
  for dir in /etc/tmpfiles.d /run/tmpfiles.d /usr/local/lib/tmpfiles.d /usr/lib/tmpfiles.d; do
    f="${root}${dir}/${conf}"
    [ -f "${f}" ] || continue

    while IFS= read -r line; do
      ## Deliberate word-splitting of the line into fields
      # shellcheck disable=SC2086
      set -- $line

      ## Mode "-" means default, "~" and ":" prefixes are dropped (install -m - would give 0000)
      mode="${3:--}"
      mode="${mode#[~:]}"
      [ "${mode}" = '-' ] && mode=''

      case "${1-}" in
        '#'*|'') continue ;;
        d|D|q|Q|v)
          install -d -m "${mode:-0755}" "${root}${2}"
          [ "${4:--}" = '-' ] || chown "${4}" "${root}${2}" 2>/dev/null || true
          [ "${5:--}" = '-' ] || chgrp "${5}" "${root}${2}" 2>/dev/null || true
          ;;
        f|F)
          [ -f "${root}${2}" ] || install -m "${mode:-0644}" /dev/null "${root}${2}"
          [ "${4:--}" = '-' ] || chown "${4}" "${root}${2}" 2>/dev/null || true
          [ "${5:--}" = '-' ] || chgrp "${5}" "${root}${2}" 2>/dev/null || true
          ;;
      esac
    done < "${f}"

    break
  done
done
