#!/bin/bash

# flame
# Your personal electric sheep

# needs: flam3, mogrify

# to rerender some flame at a later date:
# flam3-render < flame_1686912667.flam3

# vars
x="1920" ; y="1200" # final size
mul="1" # render at what size, before downsizing
x2=$(( x * mul )) ; y2=$(( y * mul )) ; supersample="3"

# vars for --small version
if [ "$1" == "-s" ] || [ "$1" == "--small" ]; then
    x="640" ; y="400" # final small size
    mul="1" # render at what size, before downsizing
    x2=$(( x * mul )) ; y2=$(( y * mul )) ; supersample="1"
fi

# naming function
randomword()  {
    dict="/usr/share/dict/words"
    if [ -f "$dict" ]; then
        word=$(shuf -n1 "$dict" | tr -dc '[:alnum:]\n\r' | tr '[:upper:]' '[:lower:]')
        # if dict gets us null length then replace with something else
        [ -z "$word" ] && word="$RANDOM"
    else # there is no dict file
        word="$RANDOM"
    fi
    echo "$word"
}

# nonoptional store
keep="$HOME/data/flames" && mkdir -p "$keep"
cd "$keep" || exit

# benchmark start
START=$(date +%s.%N)

# checks
command -v flam3-genome >/dev/null 2>&1 || { echo "I need flam3-genome, exiting." >&2; exit 1; }
command -v flam3-render >/dev/null 2>&1 || { echo "I need flam3-render, exiting." >&2; exit 1; }
command -v mogrify >/dev/null 2>&1 || { echo "I need imagemagick mogrify, exiting." >&2; exit 1; }
command -v nitrogen >/dev/null 2>&1 || { echo "I'd like nitrogen" >&2; }

# tmp dir
tmpdir="/tmp/$RANDOM-$$"
trap '[ -n "$tmpdir" ] && rm -fr "$tmpdir"' EXIT
mkdir -m 700 "$tmpdir" || { echo '!! unable to create a tmpdir' >&2; tmpdir=; exit 1; }

# prepare template flam (reduce supersample to 1 to speedup stuff)
cd "$tmpdir" || exit

echo "<pick version=\"FLAM3-LNX-3.0.1.\">
<flame version=\"FLAM3-LNX-3.0.1.\" time=\"0\" size=\"$x2 $y2\" supersample=\"$supersample\" filter=\"1\" filter_shape=\"gaussian\" temporal_filter_type=\"gaussian\" temporal_filter_width=\"1\" quality=\"1000\" passes=\"10\" temporal_samples=\"0\" background=\"0.19 0.25 0.29\" highlight_power=\"-1\" vibrancy=\"-1\">
</flame>
</pick>" > min.flam3

# rgb(50, 65, 74) 255=max => 50/255 => 0.196, 0.254, 0.29

# action
cd "$tmpdir" || exit

env template=min.flam3 flam3-genome > real.flam3


nice -n 10 env bpc=16 transparency=1 flam3-render < real.flam3 || exit

# store
word="$(randomword)"
name="flame_$(date +%y%m%d-%H%M)_${word}"
cp 00000.png "$keep/$name.png"
cp real.flam3 "$keep/$name.flam3"

# scale down
mogrify -resize ${x}x "$keep/$name.png"

# set wall
nitrogen --set-tiled --set-color="#29353B" "$keep/$name.png" > /dev/null 2>&1 && wbarRestart > /dev/null 2>&1
 # 	--save : Saves the background permanently in the config. Only used with one of the --set-xxx options.

# benchmark end
END=$(date +%s.%N)
DIFF=$(echo "scale=0; ($END - $START)/1" | bc)
echo "$name done in $DIFF seconds"
echo