#!/bin/bash
## An Imagemagick Script To Generate Wallpapers.
## Based on https://github.com/adi1090x/canvas by Aditya Shakya (adi1090x)
## Modified by Daniel Napora for Mabox Linux to run from menu


CONFIG_DIR="$HOME/.config/mabox/tools/"
CONFIG_FILE="$CONFIG_DIR/mb-canvas.cfg"
mkdir -p $CONFIG_DIR
if [ ! -f $CONFIG_FILE ]; then
cat <<EOF > ${CONFIG_FILE}
# Imagetype extension avif or png
# avif (recommended) faster and much smaller size
extenstion=avif
# Show preview window, and then decide to set as wallpaper or not
# if no denerated wallpaper will be applied immadietely
# yes (recommended) or no
show_preview=yes
EOF
fi
source <(grep = $CONFIG_FILE)

extension=${extension:-avif}
show_preview=${show_preview:-yes}


case $LANG in
    pl*)
    _IMWG="Generator Tapet"
    _PICKCOLOR="Pobierz kolor z ekranu"
    _PICKCOLORS="Pobierz kolory z ekranu"
    _PICKEDCOLOR="Pobrany kolor"
    _PICKNEXT="Pobierz nastepny"
    _PICKEDALL="Generuję tapetę..."
    _SETASWP="Ustawić jako tapetę?"
    _YES="Tak"
    _NO="Nie"
    ;;
    *)
    _IMWG="ImageMagick Wallpaper Generator"
    _PICKCOLOR="Pick color from screen"
    _PICKCOLORS="Pick colors from screen"
    _PICKEDCOLOR="Picked color"
    _PICKNEXT="Please pick next..."
    _PICKEDALL="Generating Wallpaper..."
    _SETASWP="Set as Wallpaper?"
    _YES="Yes"
    _NO="No"
    ;;
esac
    
    
DIR="$(xdg-user-dir PICTURES)/imagick"

#size="$(xrandr --current | grep '*' | uniq | awk '{print $1}')"
size=$(xrandr | grep ' primary' | grep -o '[0-9]*x[0-9]*' | head -1)
name="imagick_$(date +%Y-%m-%d_%I-%M-%S).${extension}"
#SETTER="feh --bg-scale"; 
SETTER="nitrogen --set-scaled --save"
#picker_app="gpick -s -o --no-newline"
picker_app="gpick -pso 2>/dev/null"

if [[ ! -d "$DIR" ]]; then
	mkdir -p "$DIR"   
fi

set_bg() {
    if [[ "$show_preview" == "yes" ]];then
    X="${size%x*}"
    Y="${size#*x}"
    P_X=$((X/4))
    P_Y=$((Y/4+30))
    
    yad --title="$_SETASWP" --window-icon=mbcc --borders=0 --geometry="${P_X}x${P_Y}+200+30" \
    --picture --size=fit --filename="$DIR/$name" \
    --button="$_NO":1 --button="$_YES":2 \
    
    ODP="$?"

        if [[ "$ODP" -eq "1" ]]; then
        rm "$DIR/$name" && exit 0 
        fi
        if [[ "$ODP" -eq "2" ]]; then
            $SETTER "$DIR/$name" && exit 0
        fi
    else
		$SETTER "$DIR/$name"
    fi
}


## Pick the colors
color_picker() {
	
	if [[ "$SOLID" == "true" ]]; then
    notify-send.sh "$_IMWG" "$_PICKCOLOR" -i mbcc --expire-time=12000
		color=$($picker_app)
	elif [[ "$GRADIENT" == "true" ]] || [[ "$RGRADIENT" == "true" ]] || [[ "$TGRADIENT" == "true" ]] || "$PLASMA" == "true" ]]; then
        notify-send.sh "$_IMWG" "$_PICKCOLORS: 2" -i mbcc --expire-time=12000
		color1=$($picker_app)
        FNAME="/tmp/${color1:1:6}.png"
        magick -size 100x100 xc:"$color1" "$FNAME"
        notify-send.sh "$_PICKEDCOLOR 1" "$color1\n $_PICKNEXT..." --icon="$FNAME" --expire-time=12000
		color2=$($picker_app)
        FNAME="/tmp/${color2:1:6}.png"
        magick -size 100x100 xc:"$color2" "$FNAME"
        notify-send.sh "$_PICKEDCOLOR 2" "$color1\n $_PICKEDALL" --icon="$FNAME" --expire-time=12000
		color="$color1-$color2"
	elif [[ "$BGRADIENT" == "true" ]]; then
        notify-send.sh "$_IMWG" "$_PICKCOLORS: 4" -i mbcc --expire-time=12000
		color1=$($picker_app)
        FNAME="/tmp/${color1:1:6}.png"
        magick -size 100x100 xc:"$color1" "$FNAME"
        notify-send.sh "$_PICKEDCOLOR 1" "$color1\n $_PICKNEXT..." --icon="$FNAME" --expire-time=12000
		color2=$($picker_app)
        FNAME="/tmp/${color2:1:6}.png"
        magick -size 100x100 xc:"$color2" "$FNAME"
        notify-send.sh "$_PICKEDCOLOR 2" "$color2\n $_PICKNEXT..." --icon="$FNAME" --expire-time=12000
		color3=$($picker_app)
        FNAME="/tmp/${color3:1:6}.png"
        magick -size 100x100 xc:"$color3" "$FNAME"
        notify-send.sh "$_PICKEDCOLOR 3" "$color3\n $_PICKNEXT..." --icon="$FNAME" --expire-time=12000
		color4=$($picker_app)
        FNAME="/tmp/${color4:1:6}.png"
        magick -size 100x100 xc:"$color4" "$FNAME"
        notify-send.sh "$_PICKEDCOLOR 4" "$color4\n $_PICKEDALL" --icon="$FNAME" --expire-time=12000
	fi
}

## Get colors
get_color() {
	while true; do
				color_picker
                break
	done
}
## Generate a solid color wallpaper
solid() {
	if [[ "$RANDOMIZE" == "true" ]]; then
		get_random_color
		color="$RCOLOR"
	else
		get_color
	fi
	magick -size "$size" canvas:"$color" "$DIR/$name"
	set_bg
}

## Generate a linear gradient wallpaper
linear_gradient() {
	if [[ "$RANDOMIZE" == "true" ]]; then
		get_random_color
		color="$RCOLOR"
		
		get_random_number "360"
		angle="$RNUM"
	else
		get_color
	    angle=$(yad --center --window-icon=mbcc --title="Linear gradient" --text="\tRotation angle (default is 0):" --width=400 --scale --min-value=0 --max-value=360 --step=45 --enforce-step --inc-buttons)
	fi
    name="linear_$name"
	magick -size "$size" -define gradient:angle="${angle:-0}" gradient:"$color" "$DIR/$name"
	set_bg
}

## Generate a radial gradient wallpaper
radial_gradient() {
	if [[ "$RANDOMIZE" == "true" ]]; then
		get_random_color
		color1="$RCOLOR"
		get_random_color
		color="$color1-$RCOLOR"
		
		get_random_number "360"
		angle="$RNUM"

		getRandomShape
		shape="$RSHAPE"
	else
		get_color
		shape=$(yad --center --window-icon=mbcc --title='Choose Shape' --width=180 --height=145 --button=Ok:0 --list --no-headers --column=Shape diagonal ellipse maximum minimum | tr -d '|')
		angle=$(yad --center --window-icon=mbcc --title="Radial gradient" --text="\tRotation angle:" --width=400 --scale --min-value=0 --max-value=360 --step=45 --enforce-step --inc-buttons)
	fi
    name="radial_$name"
	magick -size "$size" -define gradient:extent="${shape:-maximum}" -define gradient:angle="${angle:-0}" radial-gradient:"$color" "$DIR/$name"
	set_bg
}

## Generate a twisted gradient wallpaper
twisted_gradient() {
	if [[ "$RANDOMIZE" == "true" ]]; then
		get_random_color
		color1="$RCOLOR"
		get_random_color
		color="$color1-$RCOLOR"
		
		get_random_number "500"
		twist="$RNUM"
	else
		get_color
        twist=$(yad --center --window-icon=mbcc --title="Radial gradient" --text="\tTwisting amount (default is 150):" --width=400 --scale --value=150 --min-value=0 --max-value=500 --step=20 --inc-buttons)
	fi
	name="twisted_$name"
    magick -size "$size" gradient:"$color" -swirl "${twist:-150}" "$DIR/$name"
	set_bg
}

## Generate a 4 point gradient wallpaper
bilinear_gradient() {
	if [[ "$RANDOMIZE" == "true" ]]; then
		get_random_color
		color1="$RCOLOR"
		get_random_color
		color2="$RCOLOR"
		get_random_color
		color3="$RCOLOR"
		get_random_color
		color4="$RCOLOR"
		
		get_random_number "2"
		if [[ "$RNUM" == "1" ]]; then
			answer="Smooth"
		else
			answer="Regular"
		fi
	else
		get_color
        answer=$(yad --title='Choose Style' --width=220 --height=120 --button=Ok:0 --list --no-headers --column=Style Smooth Regular | tr -d '|')
	fi
    name="bilinear_$name"
	if [[ $answer == "Smooth" ]] || [[ $answer == "S" ]]; then
		
		magick \( xc:"$color1" xc:"$color2" +append \) \( xc:"$color3" xc:"$color4" +append \) -append -size "$size" xc: +swap  -fx 'v.p{i/(w-1),j/(h-1)}' "$DIR/$name"
	else
		magick \( xc:"$color1" xc:"$color2" +append \) \( xc:"$color3" xc:"$color4" +append \) -append -filter triangle -resize "$size"\! "$DIR/$name"
	fi
	set_bg
}

## Generate a plasma wallpaper
plasma() {
	if [[ "$RANDOMIZE" == "true" ]]; then
		get_random_number "3"

		if [[ "$RNUM" == "1" ]]; then
			answer="Random"
		elif [[ "$RNUM" == "2" ]]; then
			answer="Twisted"
			get_random_number "500"
			twist="$RNUM"
		else
			answer="c"
			get_random_color
			color="$RCOLOR"
		fi
	else
		answer=$(yad --title='Choose Style' --width=190 --height=150 --button=Ok:0 --list --no-headers --column=Style Random Twisted 'Custom colors' | tr -d '|')
	fi
    name="plasma_$name"
	if [[ $answer == "r" ]] || [[ $answer == "Random" ]]; then
		magick -size "$size" plasma: "$DIR/$name"
	elif [[ $answer == "t" ]] || [[ $answer == "Twisted" ]]; then
		if [[ "$RANDOMIZE" != "true" ]]; then
			twist=$(yad --center --window-icon=mbcc --title="Plasma" --text="\tTwisting amount (default is 150):" --width=400 --scale --value=150 --min-value=0 --max-value=500 --step=20 --inc-buttons)
		fi
		magick -size "$size" plasma:fractal -swirl "${twist:-150}" "$DIR/$name"
	else
		if [[ "$RANDOMIZE" != "true" ]]; then
        get_color
		fi
		magick -size "$size" plasma:"$color" "$DIR/$name"
	fi
	set_bg
}

## Generate a random, multi-colored blurred/gradient wallpaper
blurred_noise() {
	if [[ "$RANDOMIZE" == "true" ]]; then
		get_random_number "30"
		blur="$RNUM"
	else
		{ echo; read -p ${ORANGE}"Enter the blur strength (maximum 30): "${BLUE} blur; }
	fi
	magick -size "100x56" xc: +noise Random "/tmp/noise.png"
	magick "/tmp/noise.png" -virtual-pixel tile -blur 0x"${blur:-14}" -auto-level -resize "$size" "$DIR/$name"	
	set_bg
}

## Generate random number lower than given parameter
get_random_number() {
	RNUM=$(( ($RANDOM % $1) + 1 ))
}

## Generate random color
get_random_color() {
	RCOLOR="#"
	for i in 1 2 3 4 5 6
	do
		get_random_number "16"
		case $RNUM in
			"1") NEXTDIGIT="1";;
			"2") NEXTDIGIT="2";;
			"3") NEXTDIGIT="3";;
			"4") NEXTDIGIT="4";;
			"5") NEXTDIGIT="5";;
			"6") NEXTDIGIT="6";;
			"7") NEXTDIGIT="7";;
			"8") NEXTDIGIT="8";;
			"9") NEXTDIGIT="9";;
			"10") NEXTDIGIT="A";;
			"11") NEXTDIGIT="B";;
			"12") NEXTDIGIT="C";;
			"13") NEXTDIGIT="D";;
			"14") NEXTDIGIT="E";;
			"15") NEXTDIGIT="F";;
			"16") NEXTDIGIT="0";;
		esac
		RCOLOR="$RCOLOR$NEXTDIGIT"
	done
}

## Generate random shape option
getRandomShape() {
	get_random_number "4"
	case $RNUM in
		"1") RSHAPE="diagonal";;
		"2") RSHAPE="ellipse";;
		"3") RSHAPE="maximum";;
		"4") RSHAPE="minimum";;
	esac
}

## Generate random wallpaper
randomize() {
	get_random_number "7"
	case $RNUM in
		"1") solid;;
		"2") linear_gradient;;
		"3") radial_gradient;;
		"4") twisted_gradient;;
		"5") bilinear_gradient;;
		"6") plasma;;
		"7") blurred_noise;;
	esac
}


## Parse the arguments
options=$(getopt -o S:,s,l,r,t,b,p,B,h,a,R --long size:,solid,linear,radial,twisted,bilinear,plasma,blurred,help,autobg,randomize -- "$@")
eval set -- "$options"

while true; do
    case "$1" in 
        -S|--size)
            shift;
		    size=$1
            ;;
        -s|--solid)
            SOLID="true"
            COLOR=$1
            ;;
        -l|--linear)
            GRADIENT="true"
            ;;
        -r|--radial)
            RGRADIENT="true"
            ;;
        -t|--twisted)
            TGRADIENT="true"
            ;;
        -b|--bilinear)
            BGRADIENT="true"
            ;;
        -p|--plasma)
            PLASMA="true"
            ;;
        -B|--blurred)
            NOISE="true"
            ;;
        -a|--autobg)
            AUTOBG="true"
            ;;
        -R|--randomize)
            RANDOMIZE="true"
            ;;
        -h|--help)
		    usage
			exit
            ;;
        --)
            shift
            break
            ;;
    esac
    shift
done

## Main Execution


if [[ "$SOLID" == "true" ]]; then
	solid
elif [[ "$GRADIENT" == "true" ]]; then
	linear_gradient
elif [[ "$RGRADIENT" == "true" ]]; then
	radial_gradient
elif [[ "$TGRADIENT" == "true" ]]; then
	twisted_gradient
elif [[ "$BGRADIENT" == "true" ]]; then
	bilinear_gradient
elif [[ "$PLASMA" == "true" ]]; then
	plasma
elif [[ "$NOISE" == "true" ]]; then
	blurred_noise
elif [[ "$RANDOMIZE" == "true" ]]; then
	randomize
else
	usage
fi
