#!/bin/bash

. /usr/lib/shell/lib-screen.sh
. /usr/lib/shell/lib-grid.sh

splash_ctl=fbcondecor_ctl.static

main() {
    FB_THEMES="$(read_splash_themes | sort -f)"
    #grid_color_scheme light

    screen_set title1="Select a Background Theme"
    screen_set title2="Press: <Enter> to use new theme, <q> to quit, <h> for help"
    screen_set box=-s border=1

    init

    hide_tty
    clear
    redraw
    main_loop
}

init() {
    screen_init
    grid_read_new fbtheme "$FB_THEMES"
    grid_large y=3 title="FB Background Themes"
    grid_fill_y 50
    grid_finalize
}

redraw() {
    screen_draw
    grid_activate
}

restart() {
    local save_sel=$GRID_SEL
    local save_def=$GRID_DEFAULT_SEL
    init
    GRID_SEL=$save_sel
    GRID_DEFAULT_SEL=$save_def
    clear
    redraw
}

fbtheme_on_enter() {
    local theme=$1 sel=$3
    GRID_DEFAULT_SEL=$sel
    if [ -z "$SCREEN_IN_VT" ]; then
        grid_activate
        db_msg "Would set theme to %s" "$white$theme"
        return
    fi

    local term=$(fgconsole)
    

    log "term=$term  theme=$theme"

    clear
    $splash_ctl --tty=$term -t "$theme" -c setcfg 2>/dev/null
    $splash_ctl --tty=$term -t "$theme" -c setpic 2>/dev/null
    $splash_ctl --tty=$term -c on

    restart
}

read_splash_themes() {
    local src=/etc/splash

    for theme in $(ls $src); do
        
        if [ -z "$FB_RES" ]; then
            [ -z "${theme##[Ii]mages}" ] || echo $theme
            continue
        fi

        local config=$src/$theme/$FB_RES.cfg
        [ -e $config ] || continue

        local pic=$(sed -rn 's/^\s*pic=//ip' $config)
        [ "$pic" -a -e "$pic" ] || continue
        echo $theme

    done
}

HELP_PAGE=splash-select

[ "$SCREEN_IN_VT" ] && need_root "$@"

FB_RES=$(cat /sys/class/graphics/fb0/virtual_size 2>/dev/null | sed 's/,/x/')

[ "$DEBUG" ] || log_file=/dev/null

main "$@" 2>> $log_file



