#!/bin/bash
# remove previous install
rm -r ncurses*

# get up to date version
apt-get source ncurses

# check if sources obtained
if [ $? -ne 0 ]
then
   echo "+------------------------------------------------------------------------------+"
   echo "|                  Unable to get NCURSES source tree!                          |"
   echo "|       Check the available packages list in /etc/apt/sources.list.            |"
   echo "+------------------------------------------------------------------------------+"
   exit
fi

# patching the source files
cd ncurses-6.*
wget https://proj.goldencode.com/downloads/ncurses/ncurses_curses_h_in_v6.1_20200708.patch
wget https://proj.goldencode.com/downloads/ncurses/ncurses_lib_getch_c_v6.1_20200708.patch
patch include/curses.h.in ncurses_curses_h_in_v6.1_20200708.patch
patch ncurses/base/lib_getch.c ncurses_lib_getch_c_v6.1_20200708.patch

# configure and build object libraries
./configure --with-termlib CFLAGS='-fPIC -O2' --with-abi-version=6
make

# make valid reference to updated ncurses.h
cd include
ln -s curses.h ncurses.h
cd ..

echo "+------------------------------------------------------------------------------+"
echo "|                 Patched NCURSES libraries update completed.                  |"

# setting up system variable if not yet defined to use custom libraries location
if [ -z "$NCURSES_FWD_STATIC" ]
then
   rc_filename=$HOME'/.bashrc'
   echo '' >> $rc_filename
   echo '# set up patched NCURSES root location' >> $rc_filename
   echo 'export NCURSES_FWD_STATIC='$PWD >> $rc_filename
   echo "|   ---------------------------   WARNING ! --------------------------------   |"
   echo "|   The .bashrc has been changed! Please open new console to activate setup!   |"
   echo "|   ---------------------------   WARNING ! --------------------------------   |"
fi
echo "|              Please do FULL FWD rebuild to activate the changes.             |"
echo "+------------------------------------------------------------------------------+"

# back to the starting directory
cd ..
