#!/bin/bash

# Copyright 2024 Massimo Girondi massimo@girondi.net
# GNU GPL v3 license
# A script to genereate a nginx configuration from a netlify-style _redirects


# Standard nginx server config
echo "server {"
echo "  listen 80;"
echo "  listen [::]:80;"
#echo "  server_name  localhost;"
#echo "  error_log /var/log/nginx/localhost.error_log notice;"
#echo "  rewrite_log on;"
echo "  location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
}"

# Error pages
echo "  error_page  404 /404.html;"
echo "  error_page   500 502 503 504  /50x.html;"
echo "  location = /50x.html { root   /usr/share/nginx/html;}"
echo "  location = /404.html { root   /usr/share/nginx/html;}"


# If there is no _redirects, we have finished our work.
if [ ! -e _redirects ]; then
        echo "}"
        exit 0
fi

while read line; do
  # Skip empty and comment lines
  if [[ $line =~ ^# ]]; then continue; fi
  if [[ $line =~ ^/.*\ *.+ ]]; then 
          # Let the magic begins
          # This would print 1 line for each line of the _redirects file
          echo $line | sed -r "s/(\/[^ ]+) *(.*)/  rewrite \^\1$ \2;/"
  fi
done < _redirects

echo "}"

