#!/usr/bin/env bash

set -euo pipefail

TARGET="/opt/dosis2/etc/pmissync/dosis_pmis_sync.json"

# Ensure target directory exists
if [ ! -d "$(dirname "$TARGET")" ]; then
    echo "Directory does not exist: $(dirname "$TARGET")"
    exit 1
fi

# Read input
if [ "${1:-}" ] && [ -f "$1" ]; then
    # File provided
    JSON_CONTENT="$(cat "$1")"
elif [ "${1:-}" ]; then
    # Raw JSON provided
    JSON_CONTENT="$1"
else
    # Read from stdin
    JSON_CONTENT="$(cat)"
fi

if [ -z "$JSON_CONTENT" ]; then
    echo "No JSON input provided"
    exit 1
fi

# Overwrite target file
printf "%s\n" "$JSON_CONTENT" > "$TARGET"

echo "JSON successfully written to $TARGET"