#!/bin/bash
# this script populate secret on a remote machine, through ssh connection
# It search for all keywords and do replacement
# format: __RSEC_PLACEHOLDER(rsec SECRET_NAME)
#       : __RSEC_PLACEHOLDER(genpasswd example.com)
#
# only rsec/genpasswd allowed.
# secret value cannot contain | or '
#
# GPT-4o

HOST="$1"
REMOTE_FILE="$2"

if [[ -z "$HOST" || -z "$REMOTE_FILE" ]]; then
  echo "Usage: $0 <host> <remote_file>"
  echo "Usage: $0 . <file_path>"
  exit 1
fi

# Step 1: fetch file content
if [ "$HOST" = "." ]; then
    CONTENT=$(cat "$REMOTE_FILE") || exit 1
else
    CONTENT=$(ssh "$HOST" cat "$REMOTE_FILE") || exit 1
fi

# Step 2: find the placeholder
PLACEHOLDER_LINE=$(echo "$CONTENT" | grep -m1 '__RSEC_PLACEHOLDER(') || exit 0
CMD=$(echo "$PLACEHOLDER_LINE" | sed -n 's/.*__RSEC_PLACEHOLDER(\(.*\)).*/\1/p') || exit 0

# Step 3: validate command
SAFE_CMD_REGEX1='^genpasswd[A-Za-z0-9_@\. -]*$'
SAFE_CMD_REGEX2='^rsec[A-Za-z0-9_@ -]*$'
if [[ "$CMD" =~ $SAFE_CMD_REGEX1 ]] || [[ "$CMD" =~ $SAFE_CMD_REGEX2 ]]; then
    OUTPUT=$(bash -c "$CMD" 2>/dev/null) || exit $?
    ssh "$HOST" sed -i "'s|__RSEC_PLACEHOLDER([^)]*)|$OUTPUT|g'" "$REMOTE_FILE"
else
    echo "Rejected to execute unsafe command '$CMD'"
    exit 1
fi


