#!/bin/bash
PATH=$PATH:/usr/local/lib/inx
. inx_essentials
maybe_switch

    theme_chooser ()
    {
    unbold ; clear ; echo
    fig-col
    figlet "  inx Colours"
    head-col
    echo
    echo "  Here you can choose your \"default\" colour theme.."
    info-col
    echo
    echo "  Changing the colour defaults here needs a logout/login."
    echo "  In a \"live\" session, there will be an automatic re-login."
    echo
    echo "  You will be asked for confirmation, but be sure you have no"
    echo "  important work happening on *any* virtual terminal!"
    echo 
    echo "  You can return and alter your preferred theme at any time, by"
    echo "  selecting this menu."
    echo 
    echo "  Type \"f\" for \"flip\" to cycle through the available themes."
    echo
    echo "  You can still alter colours \"locally\" using the \"Flip Colours\""
    echo "  option, from most INX menus."
    echo
    echo "  This menu sets your \"default\", \"global\" theme."
    echo
    fig-col
    echo "  f: Flip to another \"default\" colour scheme."
    echo "  b: Go back to the options menu."
    echo "  y: Choose this theme as your default."
    head-col
    echo -e "\n  Type \"y\" when you see the theme you want...\n"
    echo
    info-col
    read -s -n 1 COLOUR_THEME
        case $COLOUR_THEME in
            b|B)
            if [ "$EXPORTED" = "theme" ] ; then # Called from "tools"
	        exec tools
            else		
                exec first-screen
            fi		
            ;;
            y|Y)
	    printf "  "
	    bred ; bold ; yellow
            printf "  OK to log out now on *all* terminals? (y/n)\n"
	    unbold 
            read -n 1 BE_SURE

            if [ "$BE_SURE" = "y" -o "$BE_SURE" = "Y" ] ; then
                echo "$THEME" > $HOME/.default_theme
		clear
		# This has to be done with surgically precise murder and mayhem, 
		# *specifically*, for each tty login... Filter for current user as well.
		# A general 'killall' or 'pkill' won't do :| (e.g. we don't kill ssh logins by others)
                TMPKILL=$(mktemp)
                for each in $(ps -u $(whoami) -o tty= | grep ^tty | cut -c4) 
                  do
		    ps a | grep tty"$each" | grep login | grep -v tty"$(fgconsole)" | awk '{print $1}' >> $TMPKILL
                  done
                sudo kill $(cat $TMPKILL) 2> /dev/null || true 
                rm $TMPKILL
		    
                # Now commit suicide locally, after murdering our alteregos globally...
                sudo pkill -t $(tty | cut -c6-) login
	    else
                bold ; white
                echo -e "\n  All right, not changing your default theme, then..."   
                sleep 4
                theme_chooser
            fi     
            ;;
            f|F)
            switch
	    theme_chooser
	    ;;
	    *)
	    theme_chooser
	    ;;
        esac
    }    
    theme_chooser
