#!/bin/bash

# Log management function
function manage_log()
{
    # Set log directory and file
    FCITX_LOG_DIR="$HOME/.cache/fcitx"
    FCITX_LOG="$FCITX_LOG_DIR/fcitx.log"

    # Create log directory if not exists
    mkdir -p "$FCITX_LOG_DIR"

    # Remove logs older than 7 days
    find "$FCITX_LOG_DIR" -name 'fcitx.log*' -mtime +7 -delete 2>/dev/null

    # Clear log file if it's larger than 10MB
    if [ -f "$FCITX_LOG" ] && [ $(stat -f%z "$FCITX_LOG" 2>/dev/null || stat -c%s "$FCITX_LOG" 2>/dev/null) -gt 10485760 ]; then
        : > "$FCITX_LOG"
    fi
}

# Test whether fcitx is running correctly with dbus...
function trystart()
{
    # Handle log files first
    manage_log

    fcitx-remote > /dev/null 2>&1

    if [ $? = "1" ]; then
        echo "Fcitx seems is not running"
        # Redirect both stdout and stderr to cache log file
        /usr/bin/fcitx -d 2 >> "$FCITX_LOG" 2>&1
    else
        echo "Fcitx is running correctly."
    fi
}

trystart