#!/usr/bin/env perl

# Uptime script for Konversation
# SPDX-FileCopyrightText: Magnus Romnes <gromnes@online.no>
# The script might be uncompatible with other unix variants than linux.
# only tested on Debian GNU/Linux Sid
# use the code for whatever you wish :-)

$SERVER = shift;
$TARGET = shift;

my $dbus_cmd = $ENV{'KONVERSATION_DBUS_BIN'} || 'qdbus';

$PLATFORM = `uname -s`;
chomp($PLATFORM);
if($PLATFORM eq "FreeBSD") {
	$BOOTTIME = `sysctl kern.boottime`;
	$BOOTTIME =~ s/.* sec = ([0-9]+).*/\1/;
	$TIMENOW = `date +%s`;
	$seconds = $TIMENOW - $BOOTTIME;
} else {
	$UPTIME = `cat /proc/uptime`;
	if (not $UPTIME) {
		exec $dbus_cmd, 'org.kde.konversation', '/irc', 'info', 'Could not read uptime. Check that /proc/uptime exists.';
	}
	@uparray = split(/\./, $UPTIME);
    $seconds = $uparray[0];
}

if($seconds >= 86400)
{
	$days = int($seconds/86400);
	$seconds = $seconds-($days*86400);
}
if($seconds >= 3600)
{
	$hours = int($seconds/3600);
	$seconds = $seconds-($hours*3600);
}
if($seconds > 60)
{
	$minutes = int($seconds/60);
} else {
	$minutes = 0
}
if( $days && $hours ) {
	exec $dbus_cmd, 'org.kde.konversation', '/irc', 'say', $SERVER, $TARGET, "Uptime: $days days, $hours hours and $minutes minutes";
}
elsif( !$days && $hours ) {
	exec $dbus_cmd, 'org.kde.konversation', '/irc', 'say', $SERVER, $TARGET, "Uptime: $hours hours and $minutes minutes";
}
elsif( $days && !$hours ) {
	exec $dbus_cmd, 'org.kde.konversation', '/irc', 'say', $SERVER, $TARGET, "Uptime: $days days and $minutes minutes";
}
elsif( !$days && !$hours ) {
	exec $dbus_cmd, 'org.kde.konversation', '/irc', 'say', $SERVER, $TARGET, "Uptime: $minutes minutes";
}

