#!/bin/bash

# This script will helps you without reload your sway program after below codes changed.
# NOTE: `status_command` will not work properly. Please write theese settings in configuration file.

function logout() {
    input=$(notify-send -A '1=⎋' 'Logout' 'You pressed the exit shortcut. Do you really want to exit sway? This will end your Wayland session.')
    if [[ -n $input && $input -eq 1 ]]; then
        swaymsg exit
    fi
}

function power() {
    input=$(notify-send -A '1=⏾' -A '2=⏻' -A '3=↺' 'Power' 'You pressed the power button. Do you really want to exit sway? This will end your Wayland session.')
    if [[ -n $input && $input -eq 1 ]]; then
        setsid ~/.config/sway/src/backend "lock_session" && sleep 1 && ~/.config/sway/src/backend "enter_sleep"
    elif [[ -n $input && $input -eq 2 ]]; then
        poweroff
    elif [[ -n $input && $input -eq 3 ]]; then
        reboot
    fi
}

function change_wallpaper() {
    tries=3
    while [ $tries -ge 0 ]; do
        target_splash="$(find ~/Pictures/Wallpaper-Bank/wallpapers -type f | shuf -n 1)"
        if [ -n "$target_splash" ]; then
            echo "$target_splash"
            return 0
        else
            tries=$(expr $tries - 1)
            sleep 1
        fi
    done

    logger --tag sway --priority user.warn 'backend: unable to load wallpaper. please check `~/Pictures/Wallpaper-Bank/wallpapers` directory permission.'
    return 1
}

function lock_session() {
    target_splash=$(~/.config/sway/src/backend 'change_wallpaper')
    if [ $? -ne 0 ]; then
        echo 'unable to load splash image.' >&2
        return 1
    fi
    swaylock -efF --clock -i "$target_splash"

    while :; do
        if [ -z "$(pgrep -x swaylock)" ]; then
            break
        fi
        sleep 1
    done

    ~/.config/sway/src/weather '--reload'
}

function enter_sleep() {
    if ! [ "$(systemctl is-enabled sleep.target)" == 'masked' ]; then
        # NOTE: To change SleepOperation features, please enter below commands and reboot to changes take effect.
        # `echo 'SleepOperation=suspend' | sudo tee /etc/systemd/logind.conf.d/sleep-operation.conf`
        # applicable sleep targets in SleepOperation: suspend, suspend-then-hibernate, hibernate, hybrid-sleep
        # Any Handle*Key configs will not changes take effect in this `enter_sleep` function
        # If you want reject sleep operation, please enter `systemctl mask sleep.target` commands
        # To check current SleepOperation value, please run `systemd-analyze cat-config systemd/logind.conf`
        
        vailed_target=$(find /etc/systemd -type f -exec grep '^SleepOperation' {} \; | sed 's/SleepOperation=//')
        if [ -n "$vailed_target" -a "$(systemctl is-enabled $vailed_target.target)" == 'masked' ]; then
            logger --tag sway --priority user.notice "backend: $vailed_target.target was masked. Skipping \`enter_sleep\` operation."
            return 1
        fi

        systemctl sleep
    else
        logger --tag sway --priority user.notice 'backend: sleep.target was masked. Skipping `enter_sleep` operation.'
        return 1
    fi
}

function current_sink_status() {
    if [ $(pactl list sinks | grep Active | grep -c headphones) -eq 1 ]; then echo '🎧'; fi
    if [ $(amixer get Master | grep 'Left' | grep '%' | awk '{ print $6 }' | tr -d \[ | tr -d \]) == 'on' ]; then echo '🔊'; else echo '🔈'; fi
    amixer get Master | grep 'Left' | grep '%' | awk '{ print $5 }' | tr -d \[ | tr -d \]
}

function current_playing_media() {
    if [ -z "$(playerctl --player playerctld status)" ]; then
        return 1
    fi

    current_sink_status
    echo -n 'Now'
    if [ $(playerctl --player playerctld status | grep -c 'Playing') -eq 1 ]; then echo '▶︎'; elif [ $(playerctl --player playerctld status | grep -c 'Paused') -eq 1 ]; then echo '⏸'; else echo '■'; fi

    if [ $(playerctl -a status | grep Playing | wc -l) -gt 1 ]; then
        playerctl -a status | grep Playing | wc -l
    else
        playerctl --player playerctld metadata -f '{{xesam:title}}' | cut -d: -f1
        playerctl --player playerctld metadata -f '{{xesam:album}}' | cut -d: -f1
        playerctl --player playerctld metadata -f '{{xesam:artist}}' | cut -d: -f1
    fi
}

function media_controller() {
    media_info="$(current_playing_media)"
    if [ $? -ne 0 ]; then
        notify-send -et 7000 'Media Controller' 'No players found'
        return 1
    fi

    input=$(notify-send -A '1=⏮' -A "2=$(if [ $(playerctl --player playerctld status) == 'Playing' ]; then echo '⏸'; else echo '⏵'; fi)" -A '3=⏭' 'Media Controller' "$media_info")
    if [ $(playerctl -l | wc -l) -gt 1 ]; then
        target_input=$(echo -e "ALL\n$(playerctl -l)" | rofi -dmenu -lm -mesg "Pressed No.$input button and Media Status:&#x0a;$(playerctl -a status | sed 's/\n/\#x0a/g' | cat -n)")
        if [[ -n $input && $input -eq 1 ]]; then
            if [ "$target_input" == 'ALL' ]; then
                playerctl -a previous
            else
                playerctl -p $target_input previous
            fi
        elif [[ -n $input && $input -eq 2 ]]; then
            if [ "$target_input" == 'ALL' ]; then
                playerctl -a play-pause
            else
                playerctl -p $target_input play-pause
            fi
        elif [[ -n $input && $input -eq 3 ]]; then
            if [ "$target_input" == 'ALL' ]; then
                playerctl -a next
            else
                playerctl -p $target_input next
            fi
        fi
    else
        if [[ -n $input && $input -eq 1 ]]; then
            playerctl previous
        elif [[ -n $input && $input -eq 2 ]]; then
            playerctl play-pause
        elif [[ -n $input && $input -eq 3 ]]; then
            playerctl next
        fi
    fi
}

function sinks_controller() {
    if [ $(~/.config/sway/src/change_sink 'check_current_state' 'sinks') -gt 1 -a $(~/.config/sway/src/change_sink 'check_current_state' 'inputs') -gt 0 ]; then
        input=$(notify-send -A '0=Sinks' -A '1=Volume' -A "2=$(if [ $(amixer get Master | grep 'Left' | grep '%' | awk '{ print $6 }' | tr -d \[ | tr -d \]) == 'on' ]; then echo 'Mute'; else echo 'UnMute'; fi)" -A '3=pavucontrol' 'Volume Control' "$(current_sink_status && pactl get-default-sink)")
        if [[ -n $input && $input -eq 0 ]]; then
            input=$(notify-send -A '1=Default Sinks' -A '2=Source Output' 'Sinks Controller' 'Change output source or Default sink')
            if [[ -n $input && $input -eq 1 ]]; then
                ~/.config/sway/src/change_sink 'default'
            elif [[ -n $input && $input -eq 2 ]]; then
                ~/.config/sway/src/change_sink 'per_source'
            fi
        elif [[ -n $input && $input -eq 1 ]]; then
            ~/.config/sway/src/change_sink 'change_sink_volumes'
        elif [[ -n $input && $input -eq 2 ]]; then
            ~/.config/sway/src/change_sink 'sink_mute_toggles'
        elif [[ -n $input && $input -eq 3 ]]; then
            pavucontrol
        fi
    elif [ $(~/.config/sway/src/change_sink 'check_current_state' 'sinks') -gt 1 ]; then
        input=$(notify-send -A '0=Sinks' -A '1=Volume' -A "2=$(if [ $(amixer get Master | grep 'Left' | grep '%' | awk '{ print $6 }' | tr -d \[ | tr -d \]) == 'on' ]; then echo 'Mute'; else echo 'UnMute'; fi)" -A '3=pavucontrol' 'Volume Control' "$(current_sink_status && pactl get-default-sink)")
        if [[ -n $input && $input -eq 0 ]]; then
            ~/.config/sway/src/change_sink 'default'
        elif [[ -n $input && $input -eq 1 ]]; then
            ~/.config/sway/src/change_sink 'change_sink_volumes'
        elif [[ -n $input && $input -eq 2 ]]; then
            ~/.config/sway/src/change_sink 'sink_mute_toggles'
        elif [[ -n $input && $input -eq 3 ]]; then
            pavucontrol
        fi
    else
        input=$(notify-send -A '1=Volume' -A "2=$(if [ $(amixer get Master | grep 'Left' | grep '%' | awk '{ print $6 }' | tr -d \[ | tr -d \]) == 'on' ]; then echo 'Mute'; else echo 'UnMute'; fi)" -A '3=pavucontrol' 'Volume Control' "$(current_sink_status && pactl get-default-sink)")
        echo $input
        if [[ -n $input && $input -eq 1 ]]; then
            ~/.config/sway/src/change_sink 'change_sink_volumes'
        elif [[ -n $input && $input -eq 2 ]]; then
            ~/.config/sway/src/change_sink 'sink_mute_toggles'
        elif [[ -n $input && $input -eq 3 ]]; then
            pavucontrol
        fi
    fi
}

########    DO NOT CHANGE OR REMOVE BELOW LINES    ########
#   This script will not work after changing below code   #
###########################################################
if [ $# -eq 0 ]; then                                     #
    echo "usage: $0 <function [options]>" >&2             #
    exit 127                                              #
else $@; fi                                               #
###########################################################

