#!/usr/bin/env bash
# Minify the project-root .css file and inline it between the <style> tags in index.html.
# Usage: ./build-css.sh [path/to/styles.css]   (defaults to ./styles.css)
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CSS_FILE="${1:-$ROOT/styles.css}"
HTML_FILE="$ROOT/index.html"

[[ -f "$CSS_FILE" ]]  || { echo "CSS file not found: $CSS_FILE" >&2; exit 1; }
[[ -f "$HTML_FILE" ]] || { echo "HTML file not found: $HTML_FILE" >&2; exit 1; }

# Minify, but never touch whitespace inside quoted strings ("..." or '...').
# Tokenize into: quoted string | comment | everything-else, and only collapse
# whitespace in the "everything-else" tokens. Strings pass through verbatim,
# so e.g. content:"a  b" or font-family:"Foo Bar" keep their spaces.
# (\x27 is a literal single quote; used so the perl needs no ' of its own.)
minified="$(perl -0777 -pe '
  s~
      ("(?:[^"\\]|\\.)*"|\x27(?:[^\x27\\]|\\.)*\x27)  # $1 quoted string: keep verbatim
    | (/\*.*?\*/)                                     # $2 comment: drop
    | ([^"\x27/]+|/)                                  # $3 everything else: minify
  ~
      defined $1 ? $1
    : defined $2 ? q{}
    : do { local $_ = $3;
           s/\s+/ /g;                  # collapse whitespace
           s/\s*([{}:;,>])\s*/$1/g;    # trim around punctuation/combinators
           s/;}/}/g;                   # drop semicolon before closing brace
           $_ }
  ~gesx;
  s/^\s+|\s+$//g;                       # trim the ends
' "$CSS_FILE")"

# Replace everything between <style> and </style> with the minified CSS.
STYLE="$minified" perl -0777 -i -pe '
  s{(<style>).*?(</style>)}{$1 . $ENV{STYLE} . $2}se
    or die "No <style>...</style> block found in $ARGV\n";
' "$HTML_FILE"

raw=$(wc -c < "$CSS_FILE")
min=$(printf '%s' "$minified" | wc -c)
echo "Inlined CSS into $HTML_FILE  (${raw} -> ${min} bytes minified)"
