#!/bin/bash

list_profiles() {
    grep '^profile ' "$KANSHI_CONFIG" | awk '{print $2}'
}

show_profile() {
    local profile="$1"

    awk "
    /^profile $profile / {
        show=1
    }

    show {
        print
    }

    show && /^}/ {
        exit
    }
    " "$KANSHI_CONFIG"
}

activate_profile() {
    local profile="$1"
    local backup="${KANSHI_CONFIG}.backup"
    local tmp="/tmp/kanshi-profile.conf"

    if [ ! -f "$KANSHI_CONFIG" ]; then
        return 1
    fi

    show_profile "$profile" > "$tmp"

    if [ ! -s "$tmp" ]; then
        return 1
    fi

    cp "$KANSHI_CONFIG" "$backup"
    cp "$tmp" "$KANSHI_CONFIG"

    reload_kanshi
}

reload_kanshi() {
    pkill -HUP kanshi 2>/dev/null
}

reset_config() {
    local backup="${KANSHI_CONFIG}.backup"

    if [ ! -f "$backup" ]; then
        return 1
    fi

    cp "$backup" "$KANSHI_CONFIG"
}

start_kanshi() {
    if pgrep -x kanshi >/dev/null 2>&1; then
        message "kanshi is already running."
        return 0
    fi

    if ! command -v kanshi >/dev/null 2>&1; then
        error "kanshi is not installed."
        return 1
    fi

    kanshi >/dev/null 2>&1 &

    sleep 1

    if pgrep -x kanshi >/dev/null 2>&1; then
        message "kanshi started successfully."
    else
        error "Failed to start kanshi."
        return 1
    fi
}
