#!/bin/bash # Define paths and variables CONFIG_FILE="/var/lib/cosmos/cosmos.config.json" USER=$(whoami) HOSTNAME=$(hostname) OUTPUT_FILE="/home/$USER/internal_hosts-$HOSTNAME.conf" REMOTE_SERVER="sdb-share" REMOTE_PATH="/etc/dnsmasq.d/" # Function to get IP address of an interface get_interface_ip() { local interface=$1 ip -4 addr show "$interface" 2>/dev/null | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | head -n 1 } # Prefer tailscale0, fallback to eth0 LOCAL_IP=$(get_interface_ip "tailscale0") if [[ -z "$LOCAL_IP" ]]; then LOCAL_IP=$(get_interface_ip "eth0") fi # Ensure we have a valid IP address if [[ -z "$LOCAL_IP" ]]; then echo "No valid IP address found for tailscale0 or eth0." exit 1 fi # Check if configuration file exists if [[ ! -f "$CONFIG_FILE" ]]; then echo "Configuration file not found: $CONFIG_FILE" exit 1 fi # Clear or create the output file > "$OUTPUT_FILE" # Extract *.internal routes (only enabled ones) and write in dnsmasq format jq -r '.HTTPConfig.ProxyConfig.Routes[]? | select(type == "object" and (.Host | test("\\.home$")) and ((.Disabled // false) | not)) | .Host' "$CONFIG_FILE" | while read -r host; do echo "address=/$host/$LOCAL_IP" >> "$OUTPUT_FILE" done # Generate checksums LOCAL_CHECKSUM=$(sha256sum "$OUTPUT_FILE" | awk '{print $1}') REMOTE_CHECKSUM=$(ssh guy@$REMOTE_SERVER "sha256sum $REMOTE_PATH/$(basename $OUTPUT_FILE) 2>/dev/null" | awk '{print $1}') # Compare checksums and sync if different if [[ "$LOCAL_CHECKSUM" != "$REMOTE_CHECKSUM" ]]; then # Sync the file to the remote server using rsync if rsync -avz "$OUTPUT_FILE" "guy@$REMOTE_SERVER:$REMOTE_PATH"; then echo "File updated and synced to $REMOTE_SERVER:$REMOTE_PATH" # Restart dnsmasq service on the remote server if ssh guy@$REMOTE_SERVER sudo /bin/systemctl restart dnsmasq.service; then echo "dnsmasq service restarted successfully on $REMOTE_SERVER" else echo "Failed to restart dnsmasq service on $REMOTE_SERVER" exit 1 fi else echo "Failed to sync file to $REMOTE_SERVER:$REMOTE_PATH" exit 1 fi else echo "No changes detected - skipping sync" fi