#!/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

# GPT-4o v2, allows multiple replacement
#!/bin/bash
set -euo pipefail

HOST="$1"
REMOTE_FILE="$2"
SAFE_CMD_REGEX1='^genpasswd[A-Za-z0-9_@\. -]*$'
SAFE_CMD_REGEX2='^rsec[A-Za-z0-9_@ -]*$'

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

# Create temp file for caching and cleanup later
tmp_file=$(mktemp)
trap 'rm -f "$tmp_file"' EXIT

# Step 1: SSH to remote and fetch file
if [ "$HOST" = "." ]; then
    cp "$REMOTE_FILE" "$tmp_file"
else
    scp "$HOST:$REMOTE_FILE" "$tmp_file" > /dev/null
fi

# Step 2: Replace all __RSEC_PLACEHOLDER(...) instances
# Extract all unique placeholders
placeholders=$(grep -oP '__RSEC_PLACEHOLDER\(\K[^)]+' "$tmp_file" | sort -u)

# Step 2: Replace all __RSEC_PLACEHOLDER(...) instances
grep -oP '__RSEC_PLACEHOLDER\(\K[^)]+' "$tmp_file" | sort -u | while read -r CMD; do
    echo "rsec_populate: EXEC $CMD"

    if [[ "$CMD" =~ $SAFE_CMD_REGEX1 ]] || [[ "$CMD" =~ $SAFE_CMD_REGEX2 ]]; then
        output=$(bash -c "$CMD")
    else
        echo "Rejected unsafe command: $CMD"
        exit 1
    fi

    # Escape output for sed
    safe_output=$(printf '%s\n' "$output" | sed -e 's/[\/&]/\\&/g')
    sed -i "s|__RSEC_PLACEHOLDER(${CMD})|$safe_output|g" "$tmp_file"
done

# Step 3: Upload back to remote
if [ "$HOST" = "." ]; then
    cp "$tmp_file" "$REMOTE_FILE"
else
    scp "$tmp_file" "$HOST:$REMOTE_FILE" > /dev/null
fi

# Step 4: Cleanup handled by trap
