#!/usr/bin/env bash
set -euo pipefail

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --help|-h)
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "Rotate to the next wallpaper in the configured list."
            echo ""
            echo "This script increments the currentIndex in home/wallpapers/default.nix,"
            echo "cycling through available wallpapers. Rebuild your system to apply"
            echo "the new wallpaper."
            echo ""
            echo "Options:"
            echo "  --help, -h    Show this help message"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
REPO_ROOT="${REPO_ROOT:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"
WALLPAPER_FILE="$REPO_ROOT/home/wallpapers/default.nix"

echo -e "${GREEN}Rotating wallpaper...${NC}"

# Check if file exists
if [[ ! -f "$WALLPAPER_FILE" ]]; then
    echo -e "${RED}Error: $WALLPAPER_FILE not found${NC}"
    exit 1
fi

# Get current index
CURRENT_INDEX=$(grep -oP 'currentIndex = \K\d+' "$WALLPAPER_FILE")
echo -e "Current index: ${YELLOW}$CURRENT_INDEX${NC}"

# Count wallpapers (count occurrences of "name = " in the wallpapers list)
WALLPAPER_COUNT=$(grep -c 'name = "' "$WALLPAPER_FILE")
echo -e "Total wallpapers: ${YELLOW}$WALLPAPER_COUNT${NC}"

# Calculate next index (wrap around)
NEXT_INDEX=$(( (CURRENT_INDEX + 1) % WALLPAPER_COUNT ))
echo -e "Next index: ${YELLOW}$NEXT_INDEX${NC}"

# Update the currentIndex
sed -i "s/currentIndex = $CURRENT_INDEX;/currentIndex = $NEXT_INDEX;/" "$WALLPAPER_FILE"

echo -e "${GREEN}Successfully rotated wallpaper!${NC}"
echo -e "  Old index: ${YELLOW}$CURRENT_INDEX${NC}"
echo -e "  New index: ${YELLOW}$NEXT_INDEX${NC}"
echo ""
echo "Rebuild your system to apply the new wallpaper."
