#!/bin/bash

readonly DEFAULT_NICK='parabola-user' # ASSERT: as defined in ~/.purple/accounts.xml and ~/.purple/blist.xml
readonly NETWORK='@irc.freenode.net'
readonly DEFAULT_ACCOUNT="${DEFAULT_NICK}${NETWORK}"
readonly CURRENT_NICK=$(grep '<name>.*</name>' ~/.purple/accounts.xml | sed "s|.*<name>\(.*\)${NETWORK}</name>.*|\1|")
readonly KEEP_NICK_MSG="Your Parabola IRC nick-name is currently '${CURRENT_NICK}'.\n\n\
Would you like to keep this nick-name, or choose another?\n\n\
Note that choosing another nickname will reset pidgin back to its freshly installed state."


#      gxmessage -title    "Parabola IRC Login"                     \
#                        -buttons  "Choose a different nick-name:0,Keep this nickname:1" \
#                        -default  "Choose a different nick-name"                                    \
#                        -geometry 620x460                                        \
#                        -center -wrap -ontop -sticky                             \
#                        "$KEEP_NICK_MSG"
# if   which gxmessage > /dev/null
if   which zenity > /dev/null
then if (diff ~/.purple/accounts.default.xml ~/.purple/accounts.xml > /dev/null &&    \
         diff ~/.purple/blist.default.xml    ~/.purple/blist.xml    > /dev/null  ) || \
        zenity --question --width=480                                                 \
               --title="Parabola IRC Login"                                           \
               --text="${KEEP_NICK_MSG}"                                              \
               --ok-label="Choose a different nick-name"                              \
               --cancel-label="Keep this nick-name"
     then cp ~/.purple/accounts.default.xml ~/.purple/accounts.xml
          cp ~/.purple/blist.default.xml    ~/.purple/blist.xml

          nick=$(zenity --entry --width=320          \
                        --title="Parabola IRC Login" \
                        --text="Choose a nick-name:" \
                        --entry-text=${DEFAULT_NICK} )
          nick=${nick// /} ; [ "$nick" ] || nick=${DEFAULT_NICK} ;

          sed -i "s|${DEFAULT_ACCOUNT}|${nick}${NETWORK}|" ~/.purple/accounts.xml
          sed -i "s|${DEFAULT_ACCOUNT}|${nick}${NETWORK}|" ~/.purple/blist.xml
     elif [[ "${CURRENT_NICK}" != "${DEFAULT_NICK}" ]]
     sed -i 's|^Exec=.*|Exec=pidgin|' ~/Desktop/parabola-irc.desktop
          rm $0
     fi
fi

pidgin
