#!/usr/bin/env bash
# skywallpaper — set or restore the SkyOS desktop wallpaper
#
# Usage:
#   skywallpaper                        # restore saved wallpaper (called from xinitrc)
#   skywallpaper /path/to/image.jpg     # set new wallpaper and save it
#   skywallpaper --color "#6B8FB5"      # set solid color
#   skywallpaper --reset                # reset to default blue-gray solid color
#
# Wallpaper preference is stored in ~/.config/skyos/wallpaper

CONF_DIR="$HOME/.config/skyos"
CONF_FILE="$CONF_DIR/wallpaper"
DEFAULT_COLOR="#1A2840"
WALLPAPER_DIR="/usr/share/skyos/wallpapers"

mkdir -p "$CONF_DIR"

case "${1:-}" in
    --reset)
        echo "color:$DEFAULT_COLOR" > "$CONF_FILE"
        xsetroot -solid "$DEFAULT_COLOR"
        echo "Wallpaper reset to default color."
        ;;
    --color)
        COLOR="${2:-$DEFAULT_COLOR}"
        echo "color:$COLOR" > "$CONF_FILE"
        xsetroot -solid "$COLOR"
        echo "Wallpaper set to solid $COLOR."
        ;;
    "")
        # Restore from saved config
        if [[ -f "$CONF_FILE" ]]; then
            SAVED="$(cat "$CONF_FILE")"
            if [[ "$SAVED" == color:* ]]; then
                xsetroot -solid "${SAVED#color:}"
            elif [[ -f "$SAVED" ]]; then
                feh --no-fehbg --bg-fill "$SAVED"
            else
                xsetroot -solid "$DEFAULT_COLOR"
            fi
        else
            # First run: use default wallpaper if it exists, else solid color
            if [[ -f "$WALLPAPER_DIR/skyos-default.png" ]]; then
                feh --no-fehbg --bg-fill "$WALLPAPER_DIR/skyos-default.png"
                echo "$WALLPAPER_DIR/skyos-default.png" > "$CONF_FILE"
            else
                xsetroot -solid "$DEFAULT_COLOR"
                echo "color:$DEFAULT_COLOR" > "$CONF_FILE"
            fi
        fi
        ;;
    *)
        # Set specific image file
        IMG="$1"
        if [[ ! -f "$IMG" ]]; then
            echo "Error: file not found: $IMG" >&2
            exit 1
        fi
        echo "$IMG" > "$CONF_FILE"
        feh --no-fehbg --bg-fill "$IMG"
        echo "Wallpaper set to: $IMG"
        ;;
esac
