#!/bin/bash
# Add CSP with unsafe-eval to HTTP location = / in blockscout nginx (for NPM proxy on :80)
set -e
CONFIG=/etc/nginx/sites-available/blockscout
if grep -q "Content-Security-Policy" "$CONFIG" 2>/dev/null; then
  echo "CSP already present"
else
  # Insert CSP line after add_header Cache-Control in first location = /
  sed -i '/location = \/ {/,/try_files \/index.html =404;/{
    /add_header Cache-Control "no-store, no-cache, must-revalidate"/a\
        add_header Referrer-Policy "strict-origin-when-cross-origin" always;\
        add_header Content-Security-Policy "default-src '\''self'\''; script-src '\''self'\'' '\''unsafe-inline'\'' '\''unsafe-eval'\'' https://cdn.jsdelivr.net https://unpkg.com https://cdnjs.cloudflare.com; style-src '\''self'\'' '\''unsafe-inline'\'' https://cdnjs.cloudflare.com; img-src '\''self'\'' data: https:; font-src '\''self'\'' https://cdnjs.cloudflare.com; connect-src '\''self'\'' https://blockscout.defi-oracle.io wss://blockscout.defi-oracle.io https://explorer.d-bis.org wss://explorer.d-bis.org https://rpc-http-pub.d-bis.org wss://rpc-ws-pub.d-bis.org http://192.168.11.221:8545 ws://192.168.11.221:8546;" always;
  }' "$CONFIG"
  echo "Added CSP to HTTP location = /"
fi
nginx -t && systemctl reload nginx
echo "Done"
