#!/bin/bash

starting_dir="$(pwd)"

# update NCURSES

if [ $# != 1 ]; then
   read -e -i "$starting_dir" -p "Type the directory path in which the NCURSES patch files are found: " patchpath
else
   patchpath="$1"
fi

headerpatch="${patchpath%/}/ncurses_curses_h_in_v6.1_20200708.patch"
getchpatch="${patchpath%/}/ncurses_lib_getch_c_v6.1_20200708.patch"

if [ ! -f $headerpatch ]; then
   echo "$headerpatch does not exist."
   exit
fi

if [ ! -f $getchpatch ]; then
   echo "$getchpatch does not exist."
   exit
fi

# clean up after previous installs that left trash behind
for dname in $(find . -maxdepth 1 -type d  -name "ncurses*"); do rm -fr "$dname"; done
rm -fr ncurses_*.tar.gz ncurses_*.tar.xz ncurses_*.dsc ncurses_*.asc

# install ncurses source code for this version
apt-get -q -y source ncurses

# move into the top-level source directory
srcdir=$(find . -maxdepth 1 -type d -name "ncurses*")
cd "$srcdir"

# patch the source code
patch include/curses.h.in $headerpatch
patch ncurses/base/lib_getch.c $getchpatch

# build the source code
./configure --libdir=/usr/lib --with-shared --with-abi-version=6 && make

# install it
sudo make install

# identify the .so name (it is version-specific)
full_libname=$(basename $(find lib/ -maxdepth 1 -type f -name "libncurses.so.*"))
major_libname="${full_libname%.*}"

# fixup libraries permissions to be accessible for building
sudo chmod o+rx /usr/lib/libform.so* /usr/lib/libmenu.so* /usr/lib/libncurses.so* /usr/lib/libpanel.so*

# fixup the main lib (the install process leaves it alone, but that won't work)
cd /lib/$(uname -i)-linux-gnu/
sudo cp $full_libname $full_libname.ori
sudo cp /usr/lib/$full_libname .
sudo rm $major_libname
sudo ln -s $full_libname $major_libname

cd "$starting_dir"

# cleanup
rm -fr "$srcdir" ncurses_*.tar.gz ncurses_*.tar.xz ncurses_*.dsc ncurses_*.asc
