#!/bin/sh
#
# S45persistent - Save/restore persistent data to NAND-backed /data
#
# Persistent storage (/data) is mounted by dcentos-early-init.sh.
# This script handles saving SSH keys and entropy seeds.
#
# NOTE: SSH key saving happens on STOP (shutdown/reboot), not START,
# because S50dropbear generates keys after this script starts.
#
# D-Central Technologies — DCENTos Hacker Shell v0.2.7
#

EXTERNAL_MEDIA_MARKER=${DCENTOS_EXTERNAL_MEDIA_MARKER:-/etc/dcentos/external-media-ephemeral-root}
EXTERNAL_MEDIA_READY=${DCENTOS_EXTERNAL_MEDIA_READY_FILE:-/run/dcentos/external-media-ephemeral-ready}
MOUNTS_FILE=${DCENTOS_MOUNTS_FILE:-/proc/mounts}
DATA_DIR=${DCENTOS_EXTERNAL_MEDIA_DATA_DIR:-/data}

if [ -e "$EXTERNAL_MEDIA_MARKER" ] || [ -L "$EXTERNAL_MEDIA_MARKER" ]; then
    case "$1" in
        start)
            if [ ! -f "$EXTERNAL_MEDIA_READY" ] || [ -L "$EXTERNAL_MEDIA_READY" ]; then
                echo "ERROR: external-media ephemeral-root readiness proof is absent or unsafe" >&2
                exit 1
            fi
            if ! awk -v path="$DATA_DIR" '
                $2 == path {
                    mounts++
                    if ($1 == "tmpfs" && $3 == "tmpfs") {
                        count = split($4, options, ",")
                        for (i = 1; i <= count; i++)
                            if (options[i] == "rw")
                                writable_tmpfs++
                    }
                }
                END { exit (mounts == 1 && writable_tmpfs == 1) ? 0 : 1 }
            ' "$MOUNTS_FILE"; then
                echo "ERROR: external-media /data is not exactly one writable tmpfs mount" >&2
                exit 1
            fi
            mkdir -p "$DATA_DIR/keys/dropbear" "$DATA_DIR/config" "$DATA_DIR/logs"
            echo "External-media posture: persistent save/restore disabled; /data is volatile"
            exit 0
            ;;
        stop)
            echo "External-media posture: refusing persistent SSH-key or entropy-seed writes"
            exit 0
            ;;
        restart)
            exec "$0" start
            ;;
    esac
fi

case "$1" in
    start)
        # Start: just ensure directories exist
        if [ -d /data ]; then
            mkdir -p /data/keys/dropbear /data/config /data/logs
        fi
        ;;

    stop)
        # Stop: save SSH keys and initialize first-boot entropy state.
        if ! awk '
            $2 == "/data" { mounts++ }
            $1 == "ubi0:rootfs_data" && $2 == "/data" && $3 == "ubifs" {
                backends++
                count = split($4, options, ",")
                for (i = 1; i <= count; i++)
                    if (options[i] == "rw")
                        writable = 1
            }
            END {
                exit (mounts == 1 && backends == 1 && writable) ? 0 : 1
            }
        ' "$MOUNTS_FILE"; then
            echo "ERROR: /data is not the writable persistent UBIFS volume" >&2
            exit 1
        fi
        if [ ! -d /data/keys ] || [ -L /data/keys ]; then
            echo "ERROR: persistent keys directory is absent or unsafe" >&2
            exit 1
        fi

        # Save SSH host keys to persistent storage.
        if [ -d /etc/dropbear ]; then
            mkdir -p /data/keys/dropbear
            cp /etc/dropbear/dropbear_*_host_key /data/keys/dropbear/ 2>/dev/null
            echo "SSH keys saved to persistent storage"
        fi

        # Boot-time seed-entropy rotates an existing seed.  Shutdown may create
        # the first seed when every lifecycle name is absent or finish a
        # durably credited seed whose CRNG-ready successor was deferred.  The
        # helper proves readiness, records the generating boot epoch, and must
        # never overwrite, replay, or same-boot credit a generated seed.
        if [ ! -x /usr/sbin/seed-entropy ]; then
            echo "ERROR: secure entropy-seed helper is unavailable" >&2
            exit 1
        fi
        if /usr/sbin/seed-entropy --initialize-if-missing \
            /data/keys/random-seed; then
            echo "Entropy seed is valid or its successor was initialized after CRNG readiness proof"
        else
            echo "ERROR: entropy seed was not initialized safely" >&2
            exit 1
        fi
        ;;

    restart)
        "$0" stop || exit $?
        exec "$0" start
        ;;

    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac

exit 0
