init.sh

Overview

`init.sh` is a shell script designed to initialize and run a service component named `midgard`. Its primary functions are to:

This script is typically part of a containerized or system service environment where it acts as the entry point to launch and manage the lifecycle of the `midgard` daemon.


Detailed Explanation

Script Initialization

#!/bin/sh
set -e

Genesis File Check and Setup

if [ ! -f "/blockstore/genesis.json" ]; then
  wget -O jq https://github.com/jqlang/jq/releases/download/jq-1.7.1/jq-linux64
  chmod +x jq
  mv jq /usr/bin
  wget -q -O- https://rpc-v1.ninerealms.com/genesis | jq -r .result.genesis > /blockstore/genesis.json
fi

**Important Details:**


Functions

start()

start() {
  ./midgard config.json &
  PID="$!"
}

**Usage:**

This function is called once during script execution to start the daemon.


stop()

stop() {
  echo "Catching signal and sending to PID: $PID"
  kill $PID
  while $(kill -0 $PID 2>/dev/null); do
    sleep 1
  done
}

**Usage:**

This function is triggered by signal traps to gracefully stop `midgard` before the script exits.


Signal Trapping

trap 'stop' TERM INT

Script Execution Flow

start
wait $PID

Usage Example

Assuming this script has execute permission (`chmod +x init.sh`), it can be run as:

./init.sh

This makes it ideal for container entrypoints or system service scripts.


Interaction with Other System Components


Implementation Details and Algorithms


Mermaid Flowchart Diagram

flowchart TD
    A[Start init.sh script] --> B{Is /blockstore/genesis.json present?}
    B -- No --> C[Download jq binary]
    C --> D[Make jq executable and move to /usr/bin]
    D --> E[Fetch genesis JSON from RPC endpoint]
    E --> F[Extract .result.genesis using jq]
    F --> G[Save genesis.json to /blockstore/genesis.json]
    B -- Yes --> G
    G --> H[Start midgard with config.json in background]
    H --> I[Store midgard PID]
    I --> J[Wait for midgard process]
    J --> K{Receive TERM or INT signal?}
    K -- Yes --> L[Call stop function]
    L --> M[Send SIGTERM to midgard PID]
    M --> N[Poll until midgard process exits]
    N --> O[Exit script]
    K -- No --> J

Summary

`init.sh` is a robust service initializer and manager script that ensures essential environment setup, launches the `midgard` daemon, and gracefully handles shutdowns. It integrates remote configuration fetching, process management, and signal handling, making it suitable for automated deployments and containerized environments within the broader system architecture.