#!/usr/bin/env bash

# https://olivergondza.github.io/2019/10/01/bash-strict-mode.html
set -euo pipefail
trap 'set +x; s=$?; echo >&2 "$0: Error on line "$LINENO": $BASH_COMMAND"; exit $s' ERR

# See the exact steps
set -x

# Taken from /usr/include/linux/input-event-codes.h
KEY_LEFTCTRL="29"
KEY_A="30"
KEY_LEFTALT="56"
KEY_LEFT="105"
KEY_RIGHT="106"
KEY_LEFTMETA="125"

DELAY=${DELAY:-5}
YDT=$(command -v ydotool)
YDTD=$(command -v ydotoold)
SYSRAPL=${SYSRAPL:-$(command sysrapl)}

function press() {
    sleep ${DELAY}
    ${YDT} key $1
}

output=${1:-"profile.json"}

# Start ydotoold
ydotoold &
ydotoold_pid=$!

# Start profiler
${SYSRAPL} --pid $(pidof gnome-shell) --output $output &
sysrapl_pid=$!

# Open overview
$(press "${KEY_LEFTMETA}:1 ${KEY_LEFTMETA}:0")

# Open application menu
$(press "${KEY_LEFTMETA}:1 ${KEY_A}:1 ${KEY_LEFTMETA}:0 ${KEY_A}:0")

# Close overview
$(press "${KEY_LEFTMETA}:1 ${KEY_LEFTMETA}:0")

# Switch to workspace on the right
$(press "${KEY_LEFTCTRL}:1 ${KEY_LEFTALT}:1 ${KEY_RIGHT}:1 ${KEY_LEFTCTRL}:0 ${KEY_LEFTALT}:0 ${KEY_RIGHT}:0")

# Switch to workspace on the left
$(press "${KEY_LEFTCTRL}:1 ${KEY_LEFTALT}:1 ${KEY_LEFT}:1 ${KEY_LEFTCTRL}:0 ${KEY_LEFTALT}:0 ${KEY_LEFT}:0")

sleep ${DELAY}

kill -s INT ${sysrapl_pid}
kill ${ydotoold_pid}
