#!/usr/bin/env sh

mod="Mod4"
modemod="Mod1"
term=${TERMINAL:-foot}
time_to_lockscreen=300
time_to_screendim=600
time_to_suspend=900

## OPTIONS
riverctl spawn "dbus-update-activation-environment SEATD_SOCK DISPLAY WAYLAND_DISPLAY XDG_CURRENT_DESKTOP=river"
riverctl focus-follows-cursor normal
riverctl set-cursor-warp on-output-change
riverctl hide-cursor when-typing enabled
riverctl attach-mode bottom

# Set background and border color
riverctl background-color 0x000000
riverctl border-width 1
riverctl border-color-focused 0xffffff
riverctl border-color-unfocused 0x586e75
# Set repeat rate
riverctl set-repeat 75 300
# Make certain views start floating
riverctl float-filter-add app-id float
# riverctl float-filter-add title "popup title with spaces"
# # Set app-ids and titles of views which should use client side decorations
# riverctl csd-filter-add app-id "gedit"
riverctl csd-filter-remove app-id "org.pwmt.zathura"

## DEBUG
# Reload river configuration
riverctl map normal $mod+Shift F12 spawn "$HOME/.config/river/init"

## HOTKEYS
# close focused view
riverctl map normal $mod+Shift C close

# Open terminal
riverctl map normal $mod Return spawn "$term"
# Open floating terminal
riverctl map normal $mod+Control Return spawn "$term start --class float"

# Open run menu
riverctl map normal $mod Space spawn "bemenu-run"

# Toggle status bar
riverctl map normal $mod F7 spawn "killall -SIGUSR1 waybar"

# Switch to lockscreen
riverctl map normal $mod X spawn "lockscreen"

# Open logout script
riverctl map normal $mod backspace spawn "powermenu"

# Open Bookmark search
riverctl map normal None XF86Search spawn "qutedmenu"
riverctl map normal $mod+Shift O spawn "qutedmenu"

# Open clipboard history
riverctl map normal $mod+Shift Space spawn "clipman pick --tool=bemenu"

# Open floating calculator
riverctl map normal $mod+Shift R spawn "$term start --class float -e qalc"

# Open emoji picker
riverctl map normal $mod+Shift E spawn "bemoji -nt"

# Open translation helper
riverctl map normal $mod+Shift T spawn "bemenu-translate"

# Desktop theming
# shellcheck disable=SC2016
riverctl map normal $mod+Shift S spawn 'flavourchoose'

# Password dropdown frontend
riverctl map normal $mod+Shift P spawn "pass-pick"

# File upload
riverctl map normal $mod+Shift U spawn "$term start --class float -e sharefile | xargs notify-send"

# # Screenshot
riverctl map normal None Print spawn "screenshot"
riverctl map normal Shift Print spawn "screenshot | sharefile -"
riverctl map normal $mod Print spawn "screenshot region"
riverctl map normal $mod+Shift Print spawn "screenshot region | sharefile -"

# control notification daemon
riverctl map normal $mod N spawn "makoctl dismiss"
riverctl map normal $mod+Shift N spawn "makoctl dismiss --all"
riverctl map normal $mod+Control N spawn "makoctl restore"

# MOVEMENT
# focus the next/previous view in the layout stack
riverctl map normal $mod J focus-view next
riverctl map normal $mod K focus-view previous

# swap the focused view with the next/previous view in the layout stack
riverctl map normal $mod+Shift J swap next
riverctl map normal $mod+Shift K swap previous

# bump the focused view to the top of the layout stack
riverctl map normal $mod+Shift Return zoom

# change layout orientation
riverctl map normal $mod Up send-layout-cmd rivercarro "main-location top"
riverctl map normal $mod Right send-layout-cmd rivercarro "main-location right"
riverctl map normal $mod Down send-layout-cmd rivercarro "main-location bottom"
riverctl map normal $mod Left send-layout-cmd rivercarro "main-location left"

# snap views to screen edges
riverctl map normal $mod+Control H snap left
riverctl map normal $mod+Control J snap down
riverctl map normal $mod+Control K snap up
riverctl map normal $mod+Control L snap right

# Mod+F to toggle fullscreen
riverctl map normal $mod F toggle-fullscreen

# shellcheck disable=SC2016
# Make all connected outputs show the desktop and no windows at all
riverctl map normal $mod+Shift M spawn 'for i in $(wlopm | wc -l); do riverctl set-focused-tags $((1 << 10)); riverctl focus-output next; done; riverctl set-focused-tags $((1 << 10)); riverctl focus-output next'

# toggle float
riverctl map normal $mod+Shift v toggle-float
# Mod + Left Mouse Button to move views
riverctl map-pointer normal $mod BTN_LEFT move-view
# Mod + Right Mouse Button to resize views
riverctl map-pointer normal $mod BTN_RIGHT resize-view

### Begin resize and moving mode, for floating windows
riverctl declare-mode interact_float
riverctl map normal $modemod R enter-mode interact_float
riverctl map interact_float $modemod R enter-mode normal
# resize views on screen
riverctl map interact_float $mod H resize horizontal -100
riverctl map interact_float $mod J resize vertical 100
riverctl map interact_float $mod K resize vertical -100
riverctl map interact_float $mod L resize horizontal 100
# move views around screen
riverctl map interact_float $mod+Shift H move left 100
riverctl map interact_float $mod+Shift J move down 100
riverctl map interact_float $mod+Shift K move up 100
riverctl map interact_float $mod+Shift L move right 100
# decrease/increase the main ratio of layout
riverctl map interact_float None H send-layout-cmd rivercarro "main-ratio -0.05"
riverctl map interact_float None L send-layout-cmd rivercarro "main-ratio +0.05"
# increment/decrement the main layout
riverctl map interact_float None J send-layout-cmd rivercarro "main-count +1"
riverctl map interact_float None K send-layout-cmd rivercarro "main-count -1"
### End resize and moving mode

# focus the next/previous output
riverctl map normal $mod Period focus-output next
riverctl map normal $mod Comma focus-output previous

# send the focused view to the next/previous output
riverctl map normal $mod+Shift Period send-to-output next
riverctl map normal $mod+Shift Comma send-to-output previous

# set up 10 tags (with '0' opening the 10th one)
for i in $(seq 0 9); do
    tags=$((1 << (i - 1)))
    if [ "$i" -eq 0 ]; then tags=$((1 << 9)); fi

    # Mod+[1-9] to focus tag [0-8]
    riverctl map normal $mod "$i" set-focused-tags $tags

    # Mod+Shift+[1-9] to tag focused view with tag [0-8]
    riverctl map normal $mod+Shift "$i" set-view-tags $tags

    # Mod+Ctrl+[1-9] to toggle focus of tag [0-8]
    riverctl map normal $mod+Control "$i" toggle-focused-tags $tags

    # Mod+Shift+Ctrl+[1-9] to toggle tag [0-8] of focused view
    riverctl map normal $mod+Shift+Control "$i" toggle-view-tags $tags
done

# focus all tags
all_tags=$(((1 << 32) - 1))
riverctl map normal $mod equal set-focused-tags $all_tags
# tag focused view with all tags
riverctl map normal $mod+Shift equal set-view-tags $all_tags

# Various media key mapping examples for both normal and locked mode which do
# not have a modifier
for mode in normal locked; do
    # Eject the optical drive
    riverctl map $mode None XF86Eject spawn 'eject -T'

    riverctl map $mode None XF86AudioRaiseVolume spawn 'pactl set-sink-volume @DEFAULT_SINK@ +5%'
    riverctl map $mode None XF86AudioLowerVolume spawn 'pactl set-sink-volume @DEFAULT_SINK@ -5%'
    riverctl map $mode None XF86AudioMute spawn 'pactl set-sink-mute @DEFAULT_SINK@ toggle'

    # Control MPRIS aware media players with playerctl (https://github.com/altdesktop/playerctl)
    riverctl map $mode None XF86AudioMedia spawn 'playerctl play-pause'
    riverctl map $mode None XF86AudioPlay spawn 'playerctl play-pause'
    riverctl map $mode None XF86AudioPrev spawn 'playerctl previous'
    riverctl map $mode None XF86AudioNext spawn 'playerctl next'

    # You can control screen backlight brighness with light (https://github.com/haikarainen/light); but we prefer brightnessctl
    riverctl map $mode None XF86MonBrightnessUp spawn 'brightnessctl set 10%+'
    riverctl map $mode None XF86MonBrightnessDown spawn 'brightnessctl set 10%-'
done

# The scratchpad will live on an unused tag. Which tags are used depends on your
# config, but rivers default uses the first 9 tags.
scratch_tag=$((1 << 20))
# Toggle the scratchpad with Super+P
riverctl map normal $mod grave toggle-focused-tags ${scratch_tag}
# Send windows to the scratchpad with Super+Shift+P
riverctl map normal $mod+Shift grave set-view-tags ${scratch_tag}
# Set spawn tagmask to ensure new windows don't have the scratchpad tag unless
# explicitly set.
all_but_scratch_tag=$((((1 << 32) - 1) ^ scratch_tag))
riverctl spawn-tagmask ${all_but_scratch_tag}

# set up scratch pad for todo and 'drop-down' terminal
# call scratchpads to current workspace -- scratchpads started on i3 starting (see end of file)
# bindsym $mod+t [class="scratchpad" title="dropdown-todo"] scratchpad show
# bindsym $mod+Shift+Return [class="scratchpad" title="dropdown-terminal"] scratchpad show

## INPUT
# device (touchscreen)
# enable touch clicking for touchpads
for pad in $(riverctl list-inputs | grep -i touchpad); do
    riverctl input "$pad" events enabled
    riverctl input "$pad" tap enabled
done
for pad in $(riverctl list-inputs | grep -i touchscreen); do
    riverctl input "$pad" events enabled
    riverctl input "$pad" tap enabled
    riverctl input "$pad" drag enabled
    riverctl input "$pad" pointer-accel 0.5
done

setxkbmap -option "compose:menu"

# set a nice wallpaper
if exist swww; then
    riverctl spawn "swww init"
    outputs=$(swww query | cut -d':' -f1)
    if [ "$(echo "$outputs" | grep -c -e '^DP')" -eq 2 ] && [ -e "$HOME/pictures/wall_r.jpg" ]; then
        swww img -o "$(echo "$outputs" | tail -n1)" "$HOME/pictures/wall_l.jpg"
        swww img -o "$(echo "$outputs" | head -n1)" "$HOME/pictures/wall_r.jpg"
    elif [ -e "$HOME/pictures/wall.jpg" ]; then
        swww img "$HOME/pictures/wall.jpg"
    fi
fi

# start status bar
killall waybar
riverctl spawn waybar

# start dynamic display configuration
killall kanshi
riverctl spawn kanshi

# start redshift-like sundown warming using current location or standard values
killall wlsunset
loc=$(curl ipinfo.io | grep -e '"loc": ' | sed -e 's/^.*"loc": "\(.*\)",$/\1/')
if [ -n "$loc" ]; then
    riverctl spawn "wlsunset -l \"$(echo "$loc" | cut -d, -f1)\" -L \"$(echo "$loc" | cut -d, -f2)\""
else
    riverctl spawn "wlsunset -S \"09:00\" -s \"21:00\" -d \"3600\""
fi
unset loc

# start screen idle locking/dimming/sleep tool
killall swayidle
riverctl spawn "swayidle \
    timeout ${time_to_suspend} \"[ $(cat /sys/class/power_supply/AC/online) -eq 0 ] && systemctl suspend-then-hibernate\"
    timeout ${time_to_screendim} \"wlopm --off '*'\" \
    resume \"wlopm --on '*'\" \
    timeout ${time_to_lockscreen} \"pidof waylock || lockscreen\" \
    after-resume \"wlopm --on '*'\" \
    before-sleep \"pidof waylock || lockscreen\" &"
killall clipman
riverctl spawn "wl-paste -t text --watch clipman store"
# bash ~/.config/bin/gtktheme # setting our gtk variables
# killall polkit-gnome-authentication-agent-1
# /usr/lib/polkit-gnome/polkit-gnome-authentication-agent-1 &
# start layouting engine
killall rivercarro
riverctl spawn "rivercarro -main-ratio 0.65"
# River will send the process group of the init executable SIGTERM on exit.
riverctl default-layout rivercarro
# exec rivercarro -main-ratio 0.65 -view-padding 6 -outer-padding 6 & # -> does not work with current rivercarro version (0.1.4)
brightnessctl set 70%
