#!/bin/bash
##############################################################################
# fancy-i3lock
# -----------
# Based on the awesome sauce of https://github.com/meskarune/i3lock-fancy
# This just uses imagemagick in a container...
# because reasons...
#
# Dependencies: docker, i3lock, scrot

# :authors: Jess Frazelle, @jfrazelle
# :date: 8 June 2015
# :version: 0.0.1
##############################################################################
# fschl copy multi monitor features from
#   https://github.com/guimeira/i3lock-fancy-multimonitor/blob/master/lock
#

set -e

# subshell this shiz
(
    IMAGE=/tmp/i3lock.png

    # All options are here: http://www.imagemagick.org/Usage/blur/#blur_args
    # BLURTYPE="0x5" # 7.52s
    # BLURTYPE="0x2" # 4.39s
    BLURTYPE="5x3" # 3.80s
    # BLURTYPE="2x8" # 2.90s
    # BLURTYPE="2x3" # 2.92s

    DISPLAY_RE="([0-9]+)x([0-9]+)\\+([0-9]+)\\+([0-9]+)"
    IMAGE_RE="([0-9]+)x([0-9]+)"
    LOCK="$HOME/dotfiles/lock.png"
    LOCK_INSIDE="/root/lock.png"
    TEXT="i3session locked by @fschl"
    PARAMS=""

    # Get dimensions of the lock image:
    LOCK_IMAGE_INFO=`identify $LOCK`
    [[ $LOCK_IMAGE_INFO =~ $IMAGE_RE ]]
    IMAGE_WIDTH=${BASH_REMATCH[1]}
    IMAGE_HEIGHT=${BASH_REMATCH[2]}

    scrot $IMAGE

    # Execute xrandr to get information about the monitors:
    while read LINE
    do
        #If we are reading the line that contains the position information:
        if [[ $LINE =~ $DISPLAY_RE ]]; then
            #Extract information and append some parameters to the ones that will be given to ImageMagick:
            WIDTH=${BASH_REMATCH[1]}
            HEIGHT=${BASH_REMATCH[2]}
            X=${BASH_REMATCH[3]}
            Y=${BASH_REMATCH[4]}
            POS_X=$(($X+$WIDTH/2-$IMAGE_WIDTH/2))
            POS_Y=$(($Y+$HEIGHT/2-$IMAGE_HEIGHT/2))
            # TEXT_X=$(($X+$WIDTH/2-$TEXT_WIDTH/2))
            # TEXT_Y=$(($Y+$HEIGHT/2-$TEXT_HEIGHT/2+200))

            # PARAMS="$PARAMS '$LOCK' '-geometry' '+$POS_X+$POS_Y' '-geometry' '+$TEXT_X+$TEXT_Y' '-composite'"
            PARAMS="$PARAMS '$LOCK_INSIDE' '-geometry' '+$POS_X+$POS_Y' '-composite'"
        fi
    done <<<"`xrandr`"

    #Execute ImageMagick:
    PARAMS="'$IMAGE' '-level' '0%,100%,0.6' '-blur' '$BLURTYPE' $PARAMS '$IMAGE'"


    docker run --rm \
           -v $IMAGE:$IMAGE \
           -v $HOME/dotfiles/lock.png:/root/lock.png \
           fschl/imagemagick \
           sh -c "convert $PARAMS"

    i3lock -i $IMAGE

    rm $IMAGE
)