#!/usr/bin/env bash

# Define the version of the binary to download
VERSION="v4.0.9"

# Parse command-line arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    -e|--extensions)
      EXTENSIONS="$2"
      shift; shift
      ;;
    -d|--directory)
      DIRECTORY="$2"
      shift; shift
      ;;
    -o|--output-dir)
      OUTPUT_DIR="$2"
      shift; shift
      ;;
    *)
      echo "Unknown argument: $1"
      exit 1
      ;;
  esac
done

# Get the directory where this script is located
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo "Script directory: $SCRIPT_DIR"

OS=$(uname -s)
ARCH=$(uname -m)

# Normalize OS and ARCH identifiers
case $OS in
  "Darwin")
    OS="macos"
    ;;
  "Linux")
    OS="linux"
    ;;
  "CYGWIN"*|"MINGW"*|"MSYS"*)
    OS="windows"
    ;;
  *)
    echo "Unknown operating system: $OS"
    exit 1
    ;;
esac

case $ARCH in
  "x86_64")
    ARCH="x64"
    ;;
  "arm64"|"aarch64")
    ARCH="arm64"
    ;;
  *)
    echo "Unsupported architecture: $ARCH"
    exit 1
    ;;
esac

echo "Detected OS: $OS"
echo "Detected Architecture: $ARCH"

# Function to construct the binary download URL based on version, OS, and architecture
get_binary_url() {
  echo "https://github.com/tailwindlabs/tailwindcss/releases/download/$VERSION/tailwindcss-$OS-$ARCH"
}

# Create the 'tw' directory for storing the downloaded binary
TW_DIR="${SCRIPT_DIR}/tw"
mkdir -p "$TW_DIR"

# Set the binary path
BINARY="${TW_DIR}/tailwindcss-${OS}-${ARCH}"

# Check if the binary is already downloaded, otherwise download it
if [ ! -f "$BINARY" ]; then
  echo "Binary not found, downloading version $VERSION..."

  DOWNLOAD_URL=$(get_binary_url)

  if [ -z "$DOWNLOAD_URL" ]; then
    echo "No suitable release found for this OS and architecture."
    exit 1
  fi

  # Download the binary
  curl -L "$DOWNLOAD_URL" -o "$BINARY"
  echo "Downloaded binary to: $BINARY"
fi

# Make the binary executable
chmod +x "$BINARY"

echo "Using binary: $BINARY"
echo "Extensions: $EXTENSIONS"
echo "Directory: $DIRECTORY"
echo "Output Directory: $OUTPUT_DIR"

# Generate the minified version for production
echo "Generating minified CSS for production..."
"$BINARY" -i "${SCRIPT_DIR}/base.css" -o "${OUTPUT_DIR}/styles.css" --minify

# Create empty daisyui.css and themes.css files if they don't exist
touch "${OUTPUT_DIR}/daisyui.css"
touch "${OUTPUT_DIR}/themes.css"

echo "All CSS files generated"
