#!/bin/bash

strip_quotes() {
  local len=${#1} quotes="['"'"]' str=${!1}

  if [[ ${str:0:1} = ${str: -1} && ${str:0:1} = $quotes ]]; then
    printf -v "$1" %s "${str:1:-1}"
  fi
}

add_udev_rule() {
    # Add an udev rules file to the initcpio image. Dependencies on binaries
    # will be discovered and added.
    #   $1: path to rules file (or name of rules file)

    local rules= rule= key= value= binary=

    rules=$(PATH=/usr/lib/udev/rules.d:/lib/udev/rules.d type -P "$1")
    if [[ -z $rules ]]; then
        # complain about not found rules
        return 1
    fi

    add_file "$rules"

    while IFS=, read -ra rule; do
        # skip empty lines, comments
        [[ -z $rule || $rule = @(+([[:space:]])|#*) ]] && continue

        for pair in "${rule[@]}"; do
            IFS=' =' read -r key value <<< "$pair"
            case $key in
                RUN{program}|RUN+|IMPORT{program}|ENV{REMOVE_CMD})
                    strip_quotes 'value'
                    # just take the first word as the binary name
                    binary=${value%% *}
                    [[ ${binary:0:1} == '$' ]] && continue
                    if [[ ${binary:0:1} != '/' ]]; then
                        binary=$(PATH=/usr/lib/udev:/lib/udev type -P "$binary")
                    fi
                    add_binary "$binary"
                    ;;
            esac
        done
    done <"$rules"
}

add_systemd_unit() {
    # Add a systemd unit file to the initcpio image. Hard dependencies on binaries
    # and other unit files will be discovered and added.
    #   $1: path to rules file (or name of rules file)

    local unit= rule= entry= key= value= binary= dep=

    unit=$(PATH=/usr/lib/systemd/system:/lib/systemd/system type -P -- "$1")
    if [[ -z $unit ]]; then
        # complain about not found unit file
        return 1
    fi

    add_file "$unit"

    while IFS='=' read -r key values; do
        read -ra values <<< "$values"

        case $key in
            Requires|Wants|Sockets|OnFailure)
                map add_systemd_unit "${values[@]}"
                ;;
            Exec*)
                # don't add binaries unless they are required
                if [[ ${values[0]:0:1} != '-' ]]; then
                    add_binary "${values[0]}"
                fi
                ;;
        esac

    done <"$unit"

    # preserve reverse soft dependency
    for dep in {/usr,}/lib/systemd/system/*.wants/${unit##*/}; do
        if [[ -L $dep ]]; then
            add_symlink "$dep"
        fi
    done

    # add hard dependencies
    if [[ -d $unit.requires ]]; then
        for dep in "$unit".requires/*; do
            add_systemd_unit ${dep##*/}
        done
    fi
}

build() {
    local applet

    # from base
    add_binary /usr/lib/initcpio/busybox /bin/busybox

    for applet in $(/usr/lib/initcpio/busybox --list); do
        add_symlink "/usr/bin/$applet" busybox
    done

    # add kmod with applet symlinks
    add_binary kmod
    for applet in {dep,ins,rm,ls}mod mod{probe,info}; do
        add_symlink "/usr/bin/$applet" kmod
    done

    # these busybox applets don't work in emergency mode, use systemctl
    for applet in halt poweroff reboot shutdown; do
        add_symlink "/usr/bin/$applet" systemctl
    done

    add_binary blkid
    add_binary mount

    # use systemd as init process
    add_binary /usr/lib/systemd/systemd /init

    # used in emergency and rescue modes
    map add_binary \
        /usr/bin/journalctl \
        /usr/bin/sulogin \
        /usr/lib/systemd/systemd-shutdown

    # generators
    map add_file \
        /usr/lib/systemd/system-generators/systemd-fstab-generator \
        /usr/lib/systemd/system-generators/systemd-gpt-auto-generator \
        /usr/lib/systemd/system-generators/systemd-hibernate-resume-generator

    # udev rules
    map add_udev_rule \
            50-udev-default.rules \
            60-persistent-storage.rules \
            64-btrfs.rules \
            80-drivers.rules \
            99-systemd.rules

    # targets
    map add_systemd_unit \
            halt.target \
            initrd.target \
            kexec.target \
            poweroff.target \
            reboot.target \
            rescue.target

    # default target
    add_symlink "/usr/lib/systemd/system/default.target" "initrd.target"

    # units activated using ExecStart=
    map add_systemd_unit \
            initrd-cleanup.service \
            initrd-switch-root.target

    # units hand-picked from sysinit.target.wants
    map add_systemd_unit \
            kmod-static-nodes.service \
            systemd-modules-load.service \
            systemd-tmpfiles-setup-dev.service \
            systemd-udev-trigger.service

    # unit templates
    map add_systemd_unit \
            systemd-fsck@.service \
            systemd-hibernate-resume@.service

    # presets and drop-in snippets
    find /{etc,usr/lib}/systemd/initrd{,-preset} -type f -print0 2>/dev/null | \
        while read -d '' file; do
            add_file "$file" "${file//\/systemd\/initrd/\/systemd\/system}"
        done
}

help() {
    cat <<HELPEOF
This will install a basic systemd setup in your initramfs, and is meant to
replace the 'base', 'usr', 'udev' and 'timestamp' hooks. Other hooks with runtime
components will need to be ported, and will not work as intended.
HELPEOF
}

# vim: set ft=sh ts=4 sw=4 et:
