#!/live/bin/bash

RAW_SCREEN_HEIGHT=24
RAW_Y0=1
Y0=1
X0=1

CONF_DIR=/live/config/tsplash

QUOTE_CACHE=$CONF_DIR/quote

case $(tty) in
    */pts/*) SCREEN_IN_VT=      ;;
          *) SCREEN_IN_VT=true  ;;
esac

SCREEN_IN_VT=
do_start() {
    rm -rf $CONF_DIR
    mkdir -p "$CONF_DIR"
}

#------------------------------------------------------------------------------
#
#------------------------------------------------------------------------------
main() {
    local cmd=$1 ; shift
    local tty_num=10

    local cache=/live/config/tsplash-cache

    case $cmd in
       redraw) test -e $cache || return 0 ;;
        start) do_start                   ;;
    esac

    PATH=$PATH:/live/bin
    set_color
    trap on_exit EXIT
    hide_tty

    printf $cursor_off
    clear
    screen_init
    box  $SCREEN_BOX $lt_cyan

    local welcome_msg=$(get_welcome_msg)
    sleep .1
    ctext $((SCREEN_Y0)) "" "$welcome_msg"

    local left_press=$(mk_key_str  "Press %s to see the boot process." "Alt-F1")
    local right_press=$(mk_key_str "Press %s to return here"           "Alt-F$tty_num")

    left_text  $((SCREEN_BOTTOM))  "$left_press"
    right_text $((SCREEN_BOTTOM))  "$right_press"

    center_quote bin/lao

    exit

    local tty_num=$(tty | sed "s/[^0-9]\+//g")
    local tty_file=/live-config/tspash-tty
    test -e $tty_file || echo $tty_num $tty_file


    echo $cursor_off
    clear

    if test -e $cache; then
        cat $cache
        return
    fi

    read_distro_release /etc/initrd-release
    : ${DISTRO_BUG_REPORT_URL:=$BUG_REPORT_URL}
    : ${DISTRO_NAME:=antiX}
    : ${DISTRO_PRETTY_NAME:=antiX-17 (generic)}
    for i in 1; do
        do_welcome "$DISTRO_PRETTY_NAME"
        echo

        lao $limit

        echo
        echo -n "${grey}Press $(mk_key Alt-F1) to see the boot process."
        echo "   Press $(mk_key Alt-F$tty_num) to return here.$nc_co"
    done | tee $cache
}

#------------------------------------------------------------------------------
#
#------------------------------------------------------------------------------
mk_key() {
    local key=$1 c1=$amber c2=$lt_grey
    echo  "<$c1$key$c2>"
}

mk_key_str() {
    local str=$1  key=$2
    printf "$lt_grey$str$nc_co" "$(mk_key "$key")"
}


#------------------------------------------------------------------------------
#
#------------------------------------------------------------------------------
msg() {
    local fmt=$1 ; shift
    printf "$m_co$fmt$nc_co" "$@"
}

#------------------------------------------------------------------------------
#
#------------------------------------------------------------------------------
read_distro_release() {
    local file=$1
    test -r "$file" || return
    eval $(sed -r -n 's/^\s*([A-Z0-9_]+=)/DISTRO_\1/p' $file)
}

#------------------------------------------------------------------------------
#
#------------------------------------------------------------------------------
pq()     { echo "$hi_co$*$m_co"           ;}
#------------------------------------------------------------------------------
#
#------------------------------------------------------------------------------

#==============================================================================
#==============================================================================
#=======  OLD CODE STARTS HERE ================================================
#==============================================================================
#==============================================================================
#==============================================================================


#------------------------------------------------------------------------------
# Create the geometry of the screen
#------------------------------------------------------------------------------

screen_init() {

    : ${SCREEN_BORDER:=1}

    RAW_X0=1 ; RAW_Y0=1
    RAW_SCREEN_WIDTH=${WIDTH:-$(  stty size | cut -d" " -f2)}
    RAW_SCREEN_HEIGHT=${HEIGHT:-$(stty size | cut -d" " -f1)}
    REAL_HEIGHT=$RAW_SCREEN_HEIGHT

    if [ -z "$SCREEN_IN_VT" ]; then
        local pts_off=5
        #RAW_Y0=$((RAW_Y0 + pts_off - 4))
        RAW_SCREEN_HEIGHT=$((RAW_SCREEN_HEIGHT - pts_off))
    fi

    SCREEN_X0=$((SCREEN_BORDER + RAW_X0))
    SCREEN_Y0=$((SCREEN_BORDER + RAW_Y0))

    SCREEN_HEIGHT=$((RAW_SCREEN_HEIGHT - 2 * SCREEN_BORDER))
    SCREEN_WIDTH=$(( RAW_SCREEN_WIDTH  - 2 * SCREEN_BORDER))
    SCREEN_BOTTOM=$((RAW_SCREEN_HEIGHT - 1))

    SCREEN_BOX="$RAW_X0 $RAW_Y0 $RAW_SCREEN_WIDTH $RAW_SCREEN_HEIGHT"
}

set_color() {
    local e=$(printf "\e")
     black="$e[0;30m";    blue="$e[0;34m";    green="$e[0;32m";    cyan="$e[0;36m";
       red="$e[0;31m";  purple="$e[0;35m";    brown="$e[0;33m"; lt_gray="$e[0;37m";
   dk_gray="$e[1;30m"; lt_blue="$e[1;34m"; lt_green="$e[1;32m"; lt_cyan="$e[1;36m";
    lt_red="$e[1;31m"; magenta="$e[1;35m";   yellow="$e[1;33m";   white="$e[1;37m";
     nc_co="$e[0m";                           amber="$e[0;33m"; lt_grey="$e[0;37m";

    cheat_co=$white;      err_co=$red;       hi_co=$white;
      cmd_co=$white;     from_co=$lt_green;  mp_co=$magenta;   num_co=$magenta;
      dev_co=$magenta;   head_co=$yellow;     m_co=$lt_cyan;    ok_co=$lt_green;
       to_co=$lt_green;  warn_co=$yellow;  bold_co=$yellow;


    clear="$e[2;J"; cursor_off="$e[?25l"; cursor_on="$e[?25h"

    SCREEN_BORDER_COLOR=$grey

    printf $nc_co

}

screen_draw_box() {
    SCREEN_DID_BOX=
    [ -n "$SCREEN_BOX_STYLE" -a -n "$SCREEN_BOX" ] || return
    SCREEN_DID_BOX=true
    box $SCREEN_BOX_STYLE $SCREEN_BOX $SCREEN_BORDER_COLOR
}

# box flag x y width heigh color

#------------------------------------------------------------------------------
# Draw a box in a certain style and with a color
# Style is set with -X flags.
#------------------------------------------------------------------------------
box() {
    local flag
    while [ $# -gt 0 -a -z "${1##-*}" ]; do
        flag=$flag${1#-}
        shift
    done

    #return
    local x0=$1 y0=$2 width=$3 height=$4 color=$5

    [ "$color" ] && printf "$nc$color"

    local iwidth=$((width - 2))
    local x1=$((x0 + width - 1))

    #-- Set up line style and colors

    [ "$ASCII_ONLY" ] && flag=A$flag
    case $flag in
      Ac) local hbar=' ' vbar=' ' tl_corn=' ' bl_corn=' ' tr_corn=' ' br_corn=' ' ;;
      Ad) local hbar='=' vbar='|' tl_corn='#' bl_corn='#' tr_corn='#' br_corn='#' ;;
      A*) local hbar='-' vbar='|' tl_corn='+' bl_corn='+' tr_corn='+' br_corn='+' ;;
       c) local hbar=' ' vbar=' ' tl_corn=' ' bl_corn=' ' tr_corn=' ' br_corn=' ' ;;
       b) local hbar='━' vbar='┃' tl_corn='┏' tr_corn='┓' bl_corn='┗' br_corn='┛' ;;
       d) local hbar='═' vbar='║' tl_corn='╔' tr_corn='╗' bl_corn='╚' br_corn='╝' ;;
       *) local hbar='─' vbar='│' tl_corn='┌' tr_corn='┐' bl_corn='└' br_corn='┘' ;;
    esac

    local bar=$(printf "%${iwidth}s" | sed "s/ /$hbar/g")
    printf "\e[$y0;${x0}H$tl_corn$bar$tr_corn"
    local y
    for y in $(seq $((y0 + 1)) $((y0 + height - 2))); do
        printf "\e[$y;${x0}H$vbar"
        printf "\e[$y;${x1}H$vbar"
    done
    printf "\e[$((y0 + height - 1));${x0}H$bl_corn$bar$br_corn"
}


cruler() {
    local i y midx
    for y in $(echo "$1" | sed 's/,/ /g'); do
        y=$(($y + SCREEN_Y0)) color=$2
        midx=$((RAW_SCREEN_WIDTH/2))
        printf "\e[$y;1H$color"
        for i in $(seq 1 $midx); do
            printf $((i % 10))
        done

        for i in $(seq 1 $midx); do
            printf "\e[$y;$((RAW_SCREEN_WIDTH -i + 1))H"
            printf $((i % 10))
        done
        printf $nc
    done
}

#======================================================================
# Strings
#======================================================================

# Note, the 2nd regex helps shells that don't know about unicode as long as sed
# is unicode-aware then you are okay.  Unfortunately BusyBox sed doesn't work
# here for stripping colors.  So we CHEAT and use . instead of \x1B

str_len() {
    echo -n "$*" | sed -r -e 's/.\[[0-9;]+[mK]//g' | wc -m
}

str_rtrunc() {
    local msg=$(echo "$1" | sed -r 's/.\[[0-9;]+[mK]//g')
    local len=$2
    echo "$msg" | sed -r "s/(.{$len}).*/\1/"
}

str_ltrunc() {
    local msg=$(echo "$1" | sed -r 's/.\[[0-9;]+[mK]//g')
    local len=$2
    echo "$msg" | sed -r "s/.*(.{$len})$/\1/"
}

text_right() {
    local x=$1  y=$2 msg=$3  len=$(str_len "$3")

    local avail=$((${SCREEN_WIDTH:-78} - x + 1))
    [ $avail -lt 0 ] && avail=78
    local pad=$((avail - len))
    [ $pad -lt 0 ] && pad=0
    #msg=$(str_rtrunc "$3" $avail)
    printf "\e[$y;${x}H%s%${pad}s" "$msg" ""
}

ctext() {
    local y=$1 x0=${2:-$((RAW_SCREEN_WIDTH / 2))} msg=$3 color=$4
    local len=$(str_len "$msg")
    local x=$((1 + x0 - len/2))
    printf "$color\e[$y;${x}H$msg"
}

goto() {
    local x=${1-1}  y=${2:-1}
    printf "\e[$y;${x}H"
}

cline() {
    local y=$1 msg=$2 color=$3
    [ "$msg" ] || return
    msg=$(echo "$msg" | sed "s/<color>/$color/g")

    local x=$SCREEN_X0
    local len=$(str_len "$msg")
    local width=$SCREEN_WIDTH
    [ $len -ge $width ] && msg=$(str_rtrunc "$msg" $width)
    local pad1=$(( (width - len) / 2))
    local pad2=$((width - len - pad1))
    printf "\e[$y;${x}H$color%${pad1}s%s%${pad2}s" "" "$msg" ""
}

left_text() {
    local y=$1 x=$((SCREEN_X0 + 1))
    shift
    local msg=$(printf "$@")
    printf "\e[$y;${x}H$color$msg"
}

right_text() {
    local y=$1
    shift
    local msg=$(printf "$@")
    local len=$(str_len "$msg")
    local x=$((SCREEN_WIDTH - len + SCREEN_X0 - 1))
    printf "\e[$y;${x}H$color$msg"
}

center_quote() {
    local prog=$1

    if test -r $QUOTE_CACHE; then
        cat "$QUOTE_CACHE"
        return
    fi
    local y=$((Y0 + 4))  x0=$((RAW_SCREEN_WIDTH / 2))
    local limit=20 cnt=0  cache  width=0
    local cache_file=$CONF_DIR/quote
    while read line; do
        cnt=$((cnt + 1))
        [ $cnt -gt $limit ] && break
        local len=$(str_len "$line")
        [ $width -lt $len ] && width=$len
        cache="$cache$line\n"
        #printf "%3s  %3s  %s\n" "$len" "$width" "$line" >> log-file
    done<<Center_Quote
$($prog)
Center_Quote

    local x=$((1 + x0 - width/2))
    while read line; do
        printf "\e[$y;${x}H$line"
        y=$((y + 1))
    done<<Center_Cache | tee -a $QUOTE_CACHE
$(echo -e "$cache")
Center_Cache
}

#------------------------------------------------------------------------------
#
#------------------------------------------------------------------------------
get_welcome_msg() {
    read_distro_release /etc/initrd-release
    : ${DISTRO_BUG_REPORT_URL:=$BUG_REPORT_URL}
    : ${DISTRO_NAME:=antiX}
    : ${DISTRO_PRETTY_NAME:=antiX-17 (generic)}
    do_welcome "$DISTRO_PRETTY_NAME"
}

#------------------------------------------------------------------------------
#
#------------------------------------------------------------------------------
do_welcome() {
    local pretty_name=$1 version=$2  v_date=$3  arch
    case $(uname -m) in
          i686) arch=" 32-bit" ;;
        x86_64) arch=" 64-bit" ;;
    esac

    case $(uname -r) in
        *[pP][aA][eE]) arch="$arch pae" ;;
    esac

    pretty_name="$pretty_name$arch"
    msg  "Welcome to %s" "$(pq $pretty_name)!"
}

restore_tty() {
    [ -n "$ORIG_STTY" ] && stty $ORIG_STTY
    #printf "$nc$clear$cursor_on"
    printf "$nc_co$cursor_on"

    #printf "\e[1;1H"
}

hide_tty() {
    [ "$ORIG_STTY" ]    || ORIG_STTY=$(stty -g)
    [ "$SCREEN_IN_VT" ] || trap restart WINCH
    clear
    stty cbreak -echo
    printf $cursor_off
}

on_exit() {
    [ -n "$SET_WINDOW_TITLE" ] && erase_window_title
    [ -n "$ORIG_STTY" ] || return
    restore_tty
    printf "$nc_co\e[$((REAL_HEIGHT- 4));1H"
}


main "$@"
