#!/bin/bash
# ┏━┓┳  o┏┓┓┏━┓┳ ┳┳  ┏━┓┏━┓┳┏ 
# ┃ ┳┃  ┃ ┃ ┃  ┃━┫┃  ┃ ┃┃  ┣┻┓
# ┇━┛┇━┛┇ ┇ ┗━┛┇ ┻┇━┛┛━┛┗━┛┇ ┛
#
# http://xero.nu, requires: i3lock-color, imagemagick, scrot

#notify-send "locking..."

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
ICONSIZE=300
IC_MAX=126


LOCKDIR=$DIR/lockd


function drawIcon() {
	ICONFILE=emoji$((1 + RANDOM % $IC_MAX)).png
	convert $DIR/glitchicons/$ICONFILE -resize $ICONSIZEx$ICONSIZE $DIR/icon.png
	GLITCHICON=$DIR/icon.png

	LOCK=()
	while read LINE
	do
		if [[ "$LINE" =~ ([0-9]+)x([0-9]+)\+([0-9]+)\+([0-9]+) ]]; then
			W=${BASH_REMATCH[1]}
			H=${BASH_REMATCH[2]}
			Xoff=${BASH_REMATCH[3]}
			Yoff=${BASH_REMATCH[4]}
			if [ ! -z "$GLITCHICON" ]; then
				IW=`identify -ping -format '%w' $GLITCHICON`
				IH=`identify -ping -format '%h' $GLITCHICON`
				MIDXi=$(($W / 2 + $Xoff - $IW / 2))
				MIDYi=$(($H / 2 + $Yoff - $IH / 2))
				LOCK+=($GLITCHICON -geometry +$MIDXi+$MIDYi -composite)
			fi
		fi
	done <<<"$(xrandr)"
}

function drawImage() {
	scrot $DIR/lock.png
	convert $DIR/lock.png -scale 10% -resize 1000% $DIR/lock.jpg
	file=$DIR/lock.jpg

	function datamosh() {
		fileSize=$(wc -c < "$file")
		headerSize=1000
		skip=$(shuf -i "$headerSize"-"$fileSize" -n 1)
		count=$(shuf -i 1-10 -n 1)
		for i in $(seq 1 $count);do byteStr=$byteStr'\x'$(shuf -i 0-255 -n 1); done;   
		printf $byteStr | dd of="$file" bs=1 seek=$skip count=$count conv=notrunc >/dev/null 2>&1
	}

	steps=$((1 + RANDOM % 50))
	for i in $(seq 1 $steps);do datamosh "$file"; done

	convert $DIR/lock.jpg $DIR/lock.png >/dev/null 2>&1
	rm $DIR/lock.jpg
	file=$DIR/lock.png

	convert "$file" "${LOCK[@]}" "$file"
}

function prepare() {
        bash -c "notify-send -t 5000 'Locking...'"
        drawIcon
		drawImage
}

function lock() {
		
		PARAM=(--bar-indicator --bar-position h --bar-direction 1 --redraw-thread -t "" \
		--bar-step 100 --bar-width 100 --bar-base-width 50 --bar-max-height 100 --bar-periodic-step 50 \
		--bar-color 00000077 --keyhlcolor 00666666 --ringvercolor cc87875f --wrongcolor ffff0000 \
		--veriftext="" --wrongtext="" --noinputtext="" )

		i3lock -n "${PARAM[@]}" -i "$file" > /dev/null 2>&1
		#i3lock -n "${PARAM[@]}" -i "$file"

		find $DIR -maxdepth 1 -type f -iname '*.png' -delete

}

case "$1" in
            lock)
                prepare
                lock
                ;;
            logout)
                i3-msg exit
                ;;
            suspend)
                prepare
                systemctl suspend && lock
                ;;
            hibernate)
                prepare
                systemctl hibernate && lock
                ;;
            reboot)
                systemctl reboot
                ;;
            shutdown)
                systemctl poweroff
                ;;
            *)
                echo $1
                echo "Usage: $0 {lock|logout|suspend|hibernate|reboot|shutdown}"
                exit 2
        esac
