#!/bin/bash
# This hook checks a specific config key if its enabled or not
# It also handles the detection if /mnt/persistent-data  or /mnt/rescue-data should be taken
# For those services, where lives in rootfs and rescueos it's practible to use this hook

# Usage:
# [Service]
# ExecCondition=/opt/systemd-hooks/evtec-config-hook.sh .Interfaces.MobileBroadband.Enable

CONFIG_FILE_SUBDIR="config/config.json"
PERSISTENT_DIR="/mnt/persistent-data/evtec-ecp-data"
RESCUE_DIR="/mnt/rescue-data/evtec-ecp-data"

# Parse and check the config param
CONFIG_PARAM="$1"

if [ -z "$CONFIG_PARAM" ]; then
    echo "Please call script with the config key e.g.: ./evtec-systemd-hook.sh .Interfaces.MobileBroadband.Enable" 
    exit 1
fi

# Evaluation for the work dir
for dir in "$PERSISTENT_DIR" "$RESCUE_DIR"; do
    if [ -d "$dir" ]; then
        ECP_WORK_FILES_DIR="$dir"
        break
    fi
done

# Exit if not not detected
if [ -z "${ECP_WORK_FILES_DIR:-}" ]; then
    echo "No valid ECP work files directory found"
    exit 1
fi

# Parse config value
if [ -f "$ECP_WORK_FILES_DIR/$CONFIG_FILE_SUBDIR" ]; then
    ENABLED=$(/usr/bin/jq $CONFIG_PARAM $ECP_WORK_FILES_DIR/$CONFIG_FILE_SUBDIR | grep "true")
    
    if [ "$ENABLED" == "true" ]; then
        exit 0
    else
        exit 1
    fi
else
    echo "config.json doesn't exist in this path: \"$ECP_WORK_FILES_DIR/$CONFIG_FILE_SUBDIR\""
fi

# If the script is here, something went totally wrong, exit with fault
exit 1
