#!/bin/bash

if [ "$#" -ne 2 ]; then
  echo "Usage: $0 <localfile> <remotefile>"
  exit 1
fi

host_vars_dir="/app/host_vars"

keys=(NEBULA_CA API_KEY HOSTNAME NEBULA_CRT NEBULA_KEY SSH_PRIVATE SSH_PUBLIC)

NEBULA_CA=$(<"$host_vars_dir/ca.crt")

localfile="$1"
remotefile="$2"
remotetmp_base="/var/tmp/4server"

# Read hosts from file descriptor 3 to prevent ssh from consuming stdin
while read -r host <&3; do
  host_env_file="$host_vars_dir/$host/$host.env"

  if [ ! -f "$host_env_file" ]; then
    echo "Warning: env file for host '$host' not found at $host_env_file. Skipping."
    continue
  fi

  # Load host environment variables (supports multi-line)
  set -a
  source "$host_env_file"
  set +a

  NEBULA_KEY=$(<"$host_vars_dir/$host/$host.key")
  NEBULA_CRT=$(<"$host_vars_dir/$host/$host.crt")

  SSH_PRIVATE=$(<"$host_vars_dir/$host/$host")
  SSH_PUBLIC=$(<"$host_vars_dir/$host/$host.pub")
  
  content=$(<"$localfile")

  for key in "${keys[@]}"; do
      value="${!key}"  # indirect reference
      # Replace placeholder {{KEY}} with value using Bash's parameter expansion
      content="${content//\{\{$key\}\}/$value}"
  done

  # Copy content to remote temporary file
  remotetmp="${remotetmp_base}_${host}"
  echo "Copying to $host:$remotefile"
  echo "$content" | ssh "$host" "cat > '$remotetmp'"

  # Move temporary file to final location with doas
  ssh "$host" "doas mv '$remotetmp' '$remotefile'"

done 3< /app/host_vars/hosts

