#!/usr/bin/env bash

: "${CM_DIR:="${XDG_RUNTIME_DIR-"${TMPDIR-/tmp}"}"}"

if [[ -z $1 ]] || [[ $1 == --help ]] || [[ $1 == -h ]]; then
    cat << 'EOF'
clipctl provides controls for the clipmenud daemon.

Commands:
    enable: enable clip collection
    disable: disable clip collection
    status: returns "enabled" or "disabled"
    toggle: toggles clip collection
    version: returns major version
    cache-dir: returns the directory used for caching
EOF
    exit 0
fi

clipmenud_pid=$(pgrep -u "$(id -u)" -nf 'clipmenud$')

case $1 in
    enable|disable|toggle|status)
        if [[ -z "$clipmenud_pid" ]]; then
            echo "clipmenud is not running" >&2
            exit 2
        fi
        ;;
esac

major_version=6
cache_dir=$CM_DIR/clipmenu.$major_version.$USER
status_file=$cache_dir/status

case $1 in
    enable) kill -USR2 "$clipmenud_pid" ;;
    disable) kill -USR1 "$clipmenud_pid" ;;
    status) cat "$status_file" ;;
    toggle)
        if [[ $(clipctl status) == "enabled" ]]; then
            clipctl disable
        else
            clipctl enable
        fi
    ;;
    version) echo "$major_version" ;;
    cache-dir) echo "$cache_dir" ;;
    *)
        printf 'Unknown command: %s\n' "$1" >&2
        exit 1
    ;;
esac
