#!/usr/bin/env bash
# Link the front ends into place. Nothing is copied, so a `git pull` updates
# what you are running.
set -euo pipefail

src="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
config="${XDG_CONFIG_HOME:-$HOME/.config}"
binhome="${HOME}/.local/bin"

usage() {
    cat <<USAGE
horologion-install [quickshell|waybar|eww|bin|all]

  quickshell  link quickshell/ into a quickshell config as horologion/
  waybar      link the bar script and print the module to merge
  eww         link eww/ into your eww config
  bin         link horologion-waybar into ~/.local/bin
  all         bin + whichever of the three are already configured

USAGE
}

link() {
    local from="$1" to="$2"
    mkdir -p "$(dirname "$to")"
    if [ -e "$to" ] && [ ! -L "$to" ]; then
        echo "  ! $to exists and is not a link — leaving it alone" >&2
        return 1
    fi
    ln -sfn "$from" "$to"
    echo "  $to -> $from"
}

do_bin() {
    link "$src/bin/horologion-waybar" "$binhome/horologion-waybar"
    case ":$PATH:" in
        *":$binhome:"*) ;;
        *) echo "  note: $binhome is not on your PATH" >&2 ;;
    esac
}

do_quickshell() {
    link "$src/quickshell" "$config/quickshell/horologion"
    cat <<'NOTE'

  Add to your shell.qml:

      import qs.horologion.modules
      ...
      Horologion {}

  Or run it on its own:

      quickshell -p ~/.config/quickshell/horologion/shell.qml
NOTE
}

do_waybar() {
    link "$src/waybar/style.css" "$config/waybar/horologion.css"
    cat <<'NOTE'

  Add "custom/typikon" to a modules list, merge waybar/config.jsonc into
  your config, and @import "horologion.css" from your style.css.
NOTE
}

do_eww() {
    link "$src/eww" "$config/eww/horologion"
    cat <<'NOTE'

  Add to your eww.yuck:     (include "horologion/horologion.yuck")
  Add to your eww.scss:     @import "horologion/horologion.scss";
  Then put (horologion) in a window, or (horologion-bar) in a bar.
NOTE
}

command -v typikon >/dev/null 2>&1 || {
    echo "horologion: typikon is not on PATH." >&2
    echo "  pip install typikon" >&2
    echo "  https://git.pumpin.online/funkpower/typikon" >&2
    exit 1
}

case "${1:-all}" in
    quickshell) do_bin; do_quickshell ;;
    waybar)     do_bin; do_waybar ;;
    eww)        do_bin; do_eww ;;
    bin)        do_bin ;;
    all)
        do_bin
        [ -d "$config/quickshell" ] && do_quickshell
        [ -d "$config/waybar" ]     && do_waybar
        [ -d "$config/eww" ]        && do_eww
        ;;
    -h|--help|help) usage ;;
    *) usage; exit 2 ;;
esac
