#!/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_20060828.patch"
getchpatch="${patchpath%/}/ncurses_lib_getch_c_v5.7_20090512.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

# 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 ncurses/base/lib_getch.c $getchpatch
patch include/curses.h.in $headerpatch

# build the source code
./configure --with-shared --with-rel-version=6.0 --with-abi-version=5 && 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 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
