#!/bin/sh
# Copyright (C) 2003 Jörg Schirottke <master@kanotix.com>
# Copyright (C) 2005 Michiel Lieuwe de Boer
# Copyright (C) 2005-2006 Stefan Lippers-Hollmann <s.l-h@gmx.de>

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

USE_SSL=false # will be set through FLL_IRC_PORT used
# override tool behaviour through distro-defaults
FLL_IRC_SERVER="irc.oftc.net"
FLL_IRC_PORT="6697"
FLL_IRC_CHANNEL="#kanotix"
FLL_DISTRO_NAME="Kanotix"
[ -r /etc/default/distro ] && . /etc/default/distro

if [ "$FLL_IRC_PORT" = "6697" -o "$FLL_IRC_PORT" = "7000" -o "$FLL_IRC_PORT" = "7070" -o "$FLL_IRC_PORT" = "9999" ]; then
   USE_SSL=true
fi

# define user settings
NICK="Web-${FLL_DISTRO_NAME}$(mawk 'BEGIN{print int(1000 * rand())}')"
FALLBACK_USER="$(getent passwd 1000 | cut -d\: -f1)"
XTERM_OPT="-e"


# determine system status
DIALOG="$(which dialog)"			|| DIALOG="/usr/bin/dialog"
KDIALOG="$(which kdialog)"			|| KDIALOG="/usr/bin/kdialog"
XDIALOG="$(which Xdialog)"			|| XDIALOG="/usr/bin/Xdialog"
ZENITY="$(which zenity)"			|| ZENITY="/usr/bin/zenity"
YAD="$(which yad)"				|| YAD="/usr/bin/yad"
MKTEMP="$(which mktemp)"			|| XTERMINAL="/bin/mktemp"
SU="$(which su)"				|| SU="/bin/su"
XTERMINAL="$(which x-terminal-emulator)"	|| XTERMINAL="/usr/bin/x-terminal-emulator"

BITCHX="$(which bitchx)"			|| BITCHX="/usr/bin/bitchx"
IRSSI="$(which irssi)"				|| IRSSI="/usr/bin/irssi"
KSIRC="$(which ksirc)"				|| KSIRC="/usr/bin/ksirc"
KONVERSATION="$(which konversation)"		|| KONVERSATION="/usr/bin/konversation"
WEECHAT="$(which weechat-curses)"		|| WEECHAT="/usr/bin/weechat-curses"
XCHAT="$(which xchat)"				|| XCHAT="/usr/bin/xchat"
HEXCHAT="$(which hexchat)"			|| HEXCHAT="/usr/bin/hexchat"
ZOITECHAT="$(which zoitechat)"			|| ZOITECHAT="/usr/bin/zoitechat"

# internal functions
inputbox()
{
	# inputbox title text width height [init]
	TITLE="$1"
	TEXT="$2"
	WIDTH="$3"
	HEIGHT="$4"
	INIT="$5"
	
	if [ -n "$DISPLAY" ]; then
		if [ -x "$KDIALOG" ]; then
			"$KDIALOG" --title "$TITLE" --inputbox "$TEXT" "$INIT"
		elif [ -x "$XDIALOG" ]; then
			"$XDIALOG" --title "$TITLE" --inputbox "$TEXT" $HEIGHT $WIDTH "$INIT"
		elif [ -x "$ZENITY" ]; then
			"$ZENITY" --title="$TITLE" --entry --text="$TEXT" --entry-text="$INIT"
		elif [ -x "$YAD" ]; then
			"$YAD" --center --title="$TITLE" --entry --text="$TEXT" --entry-text="$INIT"
		fi		
	else
		"$DIALOG" --stdout --title "$TITLE" --inputbox "$TEXT" $HEIGHT $WIDTH "$INIT"
	fi
}

kanotix_irssi()
{
	TERM_TYPE="utf-8"
	#TERM_TYPE="8bit"
	IRSSICFG="$($MKTEMP -dp /tmp/ .irssi-XXXXXXXXXX)"

	CTCPS=0
	if [ -e /etc/kanotix-version ]; then
		QUITMSG="$(< /etc/kanotix-version) | http://kanotix.com"
	else
		QUITMSG="http://kanotix.com"
	fi

	cat <<_EOF_ >"$IRSSICFG/config"
servers = (
  {
    address = "$FLL_IRC_SERVER";
    chatnet = "freenode";
    port = "$FLL_IRC_PORT";
    autoconnect = "yes";
_EOF_
	# if ssl port configured then add ssl options
	if $USE_SSL; then
		cat <<_EOF_ >>"$IRSSICFG/config"
    use_ssl = "yes";
    ssl_verify = "yes";
    ssl_capath = "/etc/ssl/certs";
_EOF_
	fi
	cat <<_EOF_ >>"$IRSSICFG/config"
  }
);

chatnets = {
  freenode = {
    type = "IRC";
    max_kicks = "4";
    max_modes = "4";
    max_msgs = "1";
    max_whois = "1";
  };
};

channels = (
  { name = "#kanotix"; chatnet = "freenode"; autojoin = "yes"; }
);
_EOF_

	# See also special kanotix aliases in here, like "/IBS", "/IBV", "/IB", "/GFX", "/SND", and "/X"
	cat <<"_EOF_" >>"$IRSSICFG/config"
aliases = {
  J = "join";
  WJOIN = "join -window";
  WQUERY = "query -window";
  LEAVE = "part";
  BYE = "quit";
  EXIT = "quit";
  SIGNOFF = "quit";
  DESCRIBE = "action";
  DATE = "time";
  HOST = "userhost";
  LAST = "lastlog";
  SAY = "msg *";
  WI = "whois";
  WII = "whois $0 $0";
  WW = "whowas";
  W = "who";
  N = "names";
  M = "msg";
  T = "topic";
  C = "clear";
  CL = "clear";
  K = "kick";
  KB = "kickban";
  KN = "knockout";
  BANS = "ban";
  B = "ban";
  MUB = "unban *";
  UB = "unban";
  IG = "ignore";
  UNIG = "unignore";
  SB = "scrollback";
  UMODE = "mode $N";
  WC = "window close";
  WN = "window new hide";
  SV = "say Irssi $J ($V) - http://irssi.org/";
  GOTO = "sb goto";
  CHAT = "dcc chat";
  RUN = "SCRIPT LOAD";
  UPTIME = "eval exec - expr `date +%s` - \\$F | awk '{print \"Irssi uptime: \"int(\\\\\\$1/3600/24)\"d \"int(\\\\\\$1/3600%24)\"h \"int(\\\\\\$1/60%60)\"m \"int(\\\\\\$1%60)\"s\" }'";
  CALC = "exec - if which bc &>/dev/null\\; then echo '$*' | bc | awk '{print \"$*=\"$$1}'\\; else echo bc was not found\\; fi";
  SBAR = "STATUSBAR";
  INVITELIST = "mode $C +I";
  Q = "QUERY";
  QUIT = "foreach window /part;/quit";
  INFOBASH = "/exec -o infobash $*";
  X = "QUIT";
};

statusbar = {
  # formats:
  # when using {templates}, the template is shown only if it's argument isn't
  # empty unless no argument is given. for example {sb} is printed always,
  # but {sb $T} is printed only if $T isn't empty.

  items = {
    # start/end text in statusbars
    barstart = "{sbstart}";
    barend = "{sbend}";

    topicbarstart = "{topicsbstart}";
    topicbarend = "{topicsbend}";

    # treated "normally", you could change the time/user name to whatever
    time = "{sb $Z}";
    user = "{sb {sbnickmode $cumode}$N{sbmode $usermode}{sbaway $A}}";

    # treated specially .. window is printed with non-empty windows,
    # window_empty is printed with empty windows
    window = "{sb $winref:$itemname{sbmode $M}}";
    window_empty = "{sb $winref{sbservertag $tag}}";
    prompt = "{prompt $[.15]itemname}";
    prompt_empty = "{prompt $winname}";
    topic = " $topic";
    topic_empty = " Irssi v$J - http://irssi.org/help/";

    # all of these treated specially, they're only displayed when needed
    lag = "{sb Lag: $0-}";
    act = "{sb Act: $0-}";
    more = "-- more --";
  };

  # there's two type of statusbars. root statusbars are either at the top
  # of the screen or at the bottom of the screen. window statusbars are at
  # the top/bottom of each split window in screen.
  default = {
    # the "default statusbar" to be displayed at the bottom of the window.
    # contains all the normal items.
    window = {
      disabled = "no";

      # window, root
      type = "window";
      # top, bottom
      placement = "bottom";
      # number
      position = "1";
      # active, inactive, always
      visible = "active";

      # list of items in statusbar in the display order
      items = {
        barstart = { priority = "100"; };
        time = { };
        user = { };
        window = { };
        window_empty = { };
        lag = { priority = "-1"; };
        act = { priority = "10"; };
        more = { priority = "-1"; alignment = "right"; };
        barend = { priority = "100"; alignment = "right"; };
      };
    };

    # statusbar to use in inactive split windows
    window_inact = {
      type = "window";
      placement = "bottom";
      position = "1";
      visible = "inactive";
      items = {
        barstart = { priority = "100"; };
        window = { };
        window_empty = { };
        more = { priority = "-1"; alignment = "right"; };
        barend = { priority = "100"; alignment = "right"; };
      };
    };

    # we treat input line as yet another statusbar :) It's possible to
    # add other items before or after the input line item.
    prompt = {
      type = "root";
      placement = "bottom";
      # we want to be at the bottom always
      position = "100";
      visible = "always";
      items = {
        prompt = { priority = "-1"; };
        prompt_empty = { priority = "-1"; };
        # treated specially, this is the real input line.
        input = { priority = "10"; };
      };
    };

    # topicbar
    topic = {
      type = "root";
      placement = "top";
      position = "1";
      visible = "always";
      items = {
        topicbarstart = { priority = "100"; };
        topic = { };
        topic_empty = { };
        topicbarend = { priority = "100"; alignment = "right"; };
      };
    };
  };
};
_EOF_

	cat <<_EOF_ >>"$IRSSICFG/config"
settings = {
  core = {
    real_name = "Kanotix user";
    user_name = "kanotix";
    nick = "$NICK";
    quit_message = "$QUITMSG";
  };

  "irc/core" = { part_message = "$QUITMSG"; };
  
  "irc/dcc" = {
    dcc_upload_path = "/tmp";
    dcc_download_path = "/tmp";
    dcc_autoget = "no";
    dcc_autochat_masks = "*";
    dcc_autoget_masks = "= *";
  };
  "fe-text" = { term_type = "$TERM_TYPE"; };
  "fe-common/core" = { completion_char = ","; };
  
};
logs = { };

windows = {
  2 = {
    items = (
      {
        type = "CHANNEL";
        chat_type = "IRC";
        name = "$FLL_IRC_CHANNEL";
        tag = "freenode";
      }
    );
  };
  1 = { immortal = "yes"; name = "(status)"; level = "ALL"; };
};
mainwindows = { 2 = { first_line = "1"; lines = "47"; }; };
_EOF_

	[ "$CTCPS" -eq 0 ] && echo 'ignores = ( { level = "CTCPS"; } );' >>"$IRSSICFG/config"

	"$IRSSI" --home="$IRSSICFG"
	RETC="$?"
	rm -rf "$IRSSICFG"
	[ "$RETC" -ne 0 ] && return 127 || exit 0
}

kanotix_xchat()
{
	XCHATCFG="$($MKTEMP -dp /tmp/ .xchat2-XXXXXXXXXX)"

        if [ -e ~/.xchat2/ ]; then
		cp -r ~/.xchat2/* "$XCHATCFG/"
		# delete improper lines
	sed -i '/gui_join_dialog/d;
		/gui_slist_skip/d;
		/gui_slist_select/d;
		/irc_nick1/d;
		/irc_nick2/d;
		/irc_nick3/d;
		/irc_user_name/d;
		/irc_real_name/d' "$XCHATCFG/xchat.conf"
	fi
	cat <<_EOF_ >>"$XCHATCFG/xchat.conf"
gui_join_dialog = 0
gui_slist_select = 0
gui_slist_skip = 1
irc_nick1 = $NICK
irc_nick2 = ${NICK}_
irc_nick3 = ${NICK}__
_EOF_


	cat <<_EOF_ >"$XCHATCFG/servlist_.conf"
N=FreeNode
J=#kanotix
E=UTF-8 (Unicode)
F=63
_EOF_
	# if ssl port configured then add ssl options
	if $USE_SSL; then
		cat <<_EOF_ >>"$XCHATCFG/servlist_.conf"
D=1
_EOF_
	else
		cat <<_EOF_ >>"$XCHATCFG/servlist_.conf"
D=0
_EOF_
	fi
	cat <<_EOF_ >>"$XCHATCFG/servlist_.conf"
S=$FLL_IRC_SERVER/$FLL_IRC_PORT
_EOF_

	cat <<_EOF_ >"$XCHATCFG/commands.conf"
NAME cmd
CMD exec -o &2
_EOF_

	"$XCHAT" -d "$XCHATCFG"
	RETC="$?"
	rm -rf "$XCHATCFG"
	[ "$RETC" -ne 0 ] && return 127 || exit 0
}

kanotix_hexchat()
{
	HEXCHATCFG="$($MKTEMP -dp /tmp/ .hexchat-XXXXXXXXXX)"

        if [ -e ~/.config/hexchat/ ]; then
		cp -r ~/.config/hexchat/* "$HEXCHATCFG/"
		# delete improper lines
	sed -i '/gui_join_dialog/d;
		/gui_slist_skip/d;
		/gui_slist_select/d;
		/irc_nick1/d;
		/irc_nick2/d;
		/irc_nick3/d;
		/irc_user_name/d;
		/irc_real_name/d' "$HEXCHATCFG/hexchat.conf"
	fi
	cat <<_EOF_ >>"$HEXCHATCFG/hexchat.conf"
gui_join_dialog = 0
gui_slist_select = 0
gui_slist_skip = 1
irc_nick1 = $NICK
irc_nick2 = ${NICK}_
irc_nick3 = ${NICK}__
_EOF_


	cat <<_EOF_ >"$HEXCHATCFG/servlist.conf"
N=OFTC
J=#kanotix
E=UTF-8 (Unicode)
F=63
_EOF_
	# if ssl port configured then add ssl options
	if $USE_SSL; then
		cat <<_EOF_ >>"$HEXCHATCFG/servlist.conf"
D=1
_EOF_
	else
		cat <<_EOF_ >>"$HEXCHATCFG/servlist.conf"
D=0
_EOF_
	fi
	cat <<_EOF_ >>"$HEXCHATCFG/servlist.conf"
S=$FLL_IRC_SERVER/$FLL_IRC_PORT
_EOF_

	cat <<_EOF_ >"$HEXCHATCFG/commands.conf"
NAME cmd
CMD exec -o &2
_EOF_

	"$HEXCHAT" -d "$HEXCHATCFG"
	RETC="$?"
	rm -rf "$HEXCHATCFG"
	[ "$RETC" -ne 0 ] && return 127 || exit 0
}

kanotix_zoitechat()
{
	ZOITECHATCFG="$($MKTEMP -dp /tmp/ .zoitechat-XXXXXXXXXX)"

        if [ -e ~/.config/zoitechat/ ]; then
		cp -r ~/.config/zoitechat/* "$ZOITECHATCFG/"
		# delete improper lines
	sed -i '/gui_join_dialog/d;
		/gui_slist_skip/d;
		/gui_slist_select/d;
		/irc_nick1/d;
		/irc_nick2/d;
		/irc_nick3/d;
		/irc_user_name/d;
		/irc_real_name/d' "$ZOITECHATCFG/zoitechat.conf"
	fi
	cat <<_EOF_ >>"$ZOITECHATCFG/zoitechat.conf"
gui_join_dialog = 0
gui_slist_select = 0
gui_slist_skip = 1
irc_nick1 = $NICK
irc_nick2 = ${NICK}_
irc_nick3 = ${NICK}__
_EOF_


	cat <<_EOF_ >"$ZOITECHATCFG/servlist.conf"
N=OFTC
J=#kanotix
E=UTF-8 (Unicode)
F=63
_EOF_
	# if ssl port configured then add ssl options
	if $USE_SSL; then
		cat <<_EOF_ >>"$ZOITECHATCFG/servlist.conf"
D=1
_EOF_
	else
		cat <<_EOF_ >>"$ZOITECHATCFG/servlist.conf"
D=0
_EOF_
	fi
	cat <<_EOF_ >>"$ZOITECHATCFG/servlist.conf"
S=$FLL_IRC_SERVER/$FLL_IRC_PORT
_EOF_

	cat <<_EOF_ >"$ZOITECHATCFG/commands.conf"
NAME cmd
CMD exec -o &2
_EOF_

	"$ZOITECHAT" -d "$ZOITECHATCFG"
	RETC="$?"
	rm -rf "$ZOITECHATCFG"
	[ "$RETC" -ne 0 ] && return 127 || exit 0
}



##############################################################################
#                               int main(void);                              #
##############################################################################

# yes, this stuff is elementary
if [ -z "$DISPLAY" ]; then
	for i in "$DIALOG" "$SU"; do
		if [ ! -x "$i" ]; then
			echo "$i: missing, terminate abnormally"
			exit 999
		fi
	done
else
	for i in "$DIALOG" "$XTERMINAL" "$SU"; do
		if [ ! -x "$i" ]; then
			echo "$i: missing, terminate abnormally"
			exit 998
		fi
	done
	if ! [ -x "$XDIALOG" -o -x "$KDIALOG" -o -x "$ZENITY" -o -x "$YAD" ]; then
		echo "$XDIALOG, $KDIALOG, $ZENITY and $YAD are missing, terminate abnormally"
		exit 998
	fi
fi

if [ "$1" = "--tty" ]; then
	DISPLAY=""
fi

# are you insane?
if [ "`id -u`" = "0" ]; then
	echo "ROOOOOOOOOOOOT has landed!"
	echo ""
	echo "Don't ever call any IRC client as root"

	if [ -z "$FALLBACK" ]; then
		# yes, you deserve it - and I'm to lazy to enhance kanotix-su's features ;)
		echo "Employ fallback and start IRC as $FALLBACK_USER."
		if [ -n "$DISPLAY" ]; then
			exec $XTERMINAL $XTERM_OPT $SU -c "$0 --tty" "$FALLBACK_USER"
		else
			exec $SU -c "$0 --tty" "$FALLBACK_USER"
		fi
	else
		exit 996
	fi

	if [ "`id -u`" = "0" ]; then
		echo "you had your chance, I'm not going to start any IRC client as root"
		exit 997
	fi
fi

# choose your nick
NICK=$(inputbox "${FLL_DISTRO_NAME} IRC Chat" "Choose your nick" 50 10 "$NICK") || exit 0

# try to start your irc client
if [ -z "$DISPLAY" ]; then
	# tty
	if [ -x "$IRSSI" ]; then
		kanotix_irssi
		exit "$?"
	fi

	if [ -x "$WEECHAT" ]; then
	    [ -d ~/.weechat ] || cp -r /etc/skel/.weechat ~
	    grep -qs "ssl_dhkey_size = 2048" ~/.weechat/irc.conf && sed -i 's/\(ssl_dhkey_size =\).*/\1 1024/' ~/.weechat/irc.conf
	    [ -r ~/.weechat/irc.conf ] || cp /etc/skel/.weechat/irc.conf ~/.weechat
	    exec $WEECHAT -a "ircs://$NICK@$FLL_IRC_SERVER:$FLL_IRC_PORT/$FLL_IRC_CHANNEL"
	fi

	[ -x "$BITCHX" ] && \
		exec "$BITCHX" -c "$FLL_IRC_CHANNEL" -n "$NICK"
else
	# X11
	if [ -x "$KONVERSATION" ]; then
		if $USE_SSL; then
			exec "$KONVERSATION" --server "$FLL_IRC_SERVER" --ssl --port "$FLL_IRC_PORT" --channel "$FLL_IRC_CHANNEL" --nick "$NICK"
		else
			exec "$KONVERSATION" --server "$FLL_IRC_SERVER" --port "$FLL_IRC_PORT" --channel "$FLL_IRC_CHANNEL" --nick "$NICK"
		fi
	fi

	[ -x "$KSIRC" ] && \
		exec "$KSIRC" --server "$FLL_IRC_SERVER" --channel "$FLL_IRC_CHANNEL" --nick "$NICK"

	if [ -x "$HEXCHAT" ]; then
		kanotix_hexchat
		exit "$?"
	fi

	if [ -x "$XCHAT" ]; then
		kanotix_xchat
		exit "$?"
	fi

	if [ -x "$ZOITECHAT" ]; then
		kanotix_zoitechat
		exit "$?"
	fi

	# nasty fallback, but well - it works ;)
	exec $XTERMINAL $XTERM_OPT $0 --tty
fi

# Oops...
echo "ERROR: failed to start any suitable IRC Client"
for i in "$DIALOG" "$XDIALOG" "$BITCHX" "$IRSSI" "$KSIRC" "$KONVERSATION" "$WEECHAT" "$XCHAT" "$HEXCHAT" "$ZOITECHAT" ; do
	if [ -x "$i" ]; then
		echo "$i: found."
	else
		echo "$i: NOT found."
	fi
done

