#!/bin/bash

#set -x # Set to help debug

show_usage()
{
   cat <<EOF
Usage: $0 [-p<path>] [-fsad] [-u<user>]
Where:
p	= Use specific path instead of current directory
f	= Override thread-safe dynamically linked version with statically linked patched version containing auto_getch_refresh
s	= Set system-wide environment instead of just current user
a	= Handle setup of /etc/apt/sources.list and restore when done (requires sudo)
u	= Update the given user's .bashrc instead of current running user. Typically for when run under sudo
d	= Dry run. Just show commands.
EOF
}

# True if the variable is already exported, or - for the per-user .bashrc, which we
# append to rather than rewrite - already present in the target file.
have_var()
{
   [ -n "${!1}" ] && return 0
   [[ "$system" != true ]] && [ -f "$rc_filename" ] && grep -q "$1" "$rc_filename"
}

# Defaults
user=$USER
homedir=$HOME

# process options
while getopts "h?p:fsadu:" opt; do
   case $opt in
      p  ) target_dir=$OPTARG ;;
      f  ) patch_ncurses=true ;;
      s  ) system=true ;;
      a  ) handle_apt=true ;;
      u  ) user=$OPTARG
           homedir=$(getent passwd "$OPTARG" | cut -d: -f6)
           [ -z "$homedir" ] && { echo "Unknown user: $OPTARG" >&2; exit 1; } ;;
      d  ) dry="echo" ;;
      h | \
      \? ) show_usage && exit 1
           exit 1 ;;
   esac
done
shift $(($OPTIND - 1))

# remove previous install, if any
$dry rm -rf ncurses*

# Learn the OS so that we can handle non-Ubuntu "kind of" gracefully
. /etc/os-release
codename="$VERSION_CODENAME"
case "$codename" in
   ulyana|ulyssa|uma|una)          release="focal" ;;   # Linux Mint 20.x
   vanessa|vera|victoria|virginia) release="jammy" ;;   # Linux Mint 21.x
   wilma|xia|zara|zena)            release="noble" ;;   # Linux Mint 22.x
   *)                              release="$codename" ;;
esac
if [ "$ID" = "rhel" ]; then
   is_rhel=true
fi

# get up to date version
if [[ "$handle_apt" == true ]]; then
   apt_backup=""   # original file saved under /tmp, restored when done
   apt_created=""  # new file we added, removed when done
   if [[ -f "/etc/apt/sources.list.d/ubuntu.sources" ]]; then
      # Deb822 format (Ubuntu 24.04 and newer): widen the Types line to add deb-src
      apt_backup="/etc/apt/sources.list.d/ubuntu.sources"
      $dry cp "$apt_backup" /tmp
      $dry sed -i 's/^Types: deb$/Types: deb deb-src/' "$apt_backup"
   elif [[ -f "/etc/apt/sources.list.d/official-package-repositories.list" ]]; then
      # Some Linux distros derive a separate deb-src list from the existing deb entries
      apt_src="/etc/apt/sources.list.d/official-package-repositories.list"
      apt_created="/etc/apt/sources.list.d/deb-src.list"
      if [ -n "$dry" ]; then
         echo "grep -q '^deb-src' $apt_src ||" \
              "sed -e 's|^deb |deb-src |' $apt_src >> $apt_created"
      else
         grep -q '^deb-src' "$apt_src" || \
         sed -e 's|^deb |deb-src |' "$apt_src" >> "$apt_created"
      fi
   else
      # Legacy one-line format (Ubuntu 22.04 / 20.04 and earlier)
      apt_backup="/etc/apt/sources.list"
      $dry cp "$apt_backup" /tmp
      if [ -n "$dry" ]; then
         echo "echo \"deb-src http://archive.ubuntu.com/ubuntu $release main restricted universe multiverse\" >> /etc/apt/sources.list"
      else
         echo "deb-src http://archive.ubuntu.com/ubuntu $release main restricted universe multiverse" >> /etc/apt/sources.list
      fi
   fi
   $dry apt-get update
fi

# install ncurses source code for this version
if [ -z "$is_rhel" ]; then
   $dry apt-get -q -y source ncurses
   src_rc=$?
else
   $dry yum install -y ncurses-devel
   src_rc=$?
fi

if [[ "$handle_apt" == true ]]; then
   [ -n "$apt_backup" ]  && $dry mv "/tmp/$(basename "$apt_backup")" "$apt_backup"
   [ -n "$apt_created" ] && $dry rm -f "$apt_created"
   $dry apt-get update
fi

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

# patching the source files. Setup an array of the base configure parameters.
ncurses_configure_flags=(CFLAGS='-fPIC -O2' --with-termlib --with-abi-version=6 --disable-widec)
$dry pushd ncurses-6.* > /dev/null || { echo "Unable to enter NCURSES source directory (ncurses-6.*)!"; exit 1; }
if [[ "$patch_ncurses" == true ]]; then
   case "$release" in
      focal|jammy)   # Ubuntu 20.04 / 22.04 (ncurses 6.2 / 6.3)
          patch_h="ncurses_curses_h_in_v6.1_20200708.patch"
          patch_c="ncurses_lib_getch_c_v6.1_20200708.patch" ;;
      noble)         # Ubuntu 24.04 (ncurses 6.4)
          patch_h="ncurses_curses_h_in_v6.4+20240113.patch"
          patch_c="ncurses_lib_getch_c_v6.4+20240113.patch" ;;
      *)             # unknown / newer - assume newest, but say so
          echo "Warning: unrecognized release '$release'; using newest NCURSES patch set" >&2
          patch_h="ncurses_curses_h_in_v6.4+20240113.patch"
          patch_c="ncurses_lib_getch_c_v6.4+20240113.patch" ;;
   esac

   $dry wget https://proj.goldencode.com/downloads/ncurses/${patch_h} || { echo "Failed to download ${patch_h} patch!"; exit 1; }
   $dry wget https://proj.goldencode.com/downloads/ncurses/${patch_c} || { echo "Failed to download ${patch_c} patch!"; exit 1; }
   $dry patch include/curses.h.in "${patch_h}"
   $dry patch ncurses/base/lib_getch.c "${patch_c}"
else
   # Add configure flags for thread-safe dynamically linked ncurses
   ncurses_configure_flags+=(--with-pthread --enable-pthreads-eintr)
fi
$dry ./configure "${ncurses_configure_flags[@]}"
$dry make
make_rc=$?
if [ "$make_rc" -ne 0 ] && [ -z "$dry" ]; then
   echo "NCURSES build failed (make returned $make_rc); aborting before any environment changes." >&2
   exit 1
fi

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

if [[ "$patch_ncurses" == true ]]; then
   echo "+------------------------------------------------------------------------------+"
   echo "|                 Patched NCURSES libraries update completed.                  |"
else
   echo "+------------------------------------------------------------------------------+"
   echo "|               Thread-safe NCURSES libraries build completed.                 |"
fi

# Position minimal files if path is specified
if [[ -n "$target_dir" ]]; then
   $dry mkdir -p "$target_dir"
   $dry cp -r include "$target_dir"
   $dry cp -r lib "$target_dir"
   $dry cd "$target_dir"
   $dry chown -R "$user:$user" "$target_dir"
fi

# Set up environment variable(s) if they are not set already.
# Pick the target file first so we can also skip entries already present in it.
if [[ "$system" == true ]]; then
   rc_filename='/etc/profile.d/10-ncurses.sh'
   msg="|         The environment has been changed! Reboot to activate changes         |"
   mode="644"
else
   rc_filename="${homedir}/.bashrc"
   msg="|   The .bashrc has been changed! Please open new console to activate setup!   |"
fi

env_update=""; sudo_update=""
if ! have_var NCURSES_FWD_STATIC; then
   if [[ "$patch_ncurses" == true ]]; then
      env_update+="# set up patched NCURSES root location"$'\n'
   else
      env_update+="# set up thread-safe NCURSES root location"$'\n'
   fi
   env_update+="export NCURSES_FWD_STATIC=\"$PWD\""$'\n'
   sudo_update+="Defaults env_keep += NCURSES_FWD_STATIC"$'\n'
fi
if ! have_var NCURSES_FWD_PTHREADS && [ "$patch_ncurses" != true ]; then
   env_update+="# and set up thread-safe NCURSES_FWD_PTHREADS variable"$'\n'
   env_update+="export NCURSES_FWD_PTHREADS=true"$'\n'
   sudo_update+="Defaults env_keep += NCURSES_FWD_PTHREADS"$'\n'
fi

if [ -n "$env_update" ]; then
   if [[ "$system" == true ]]; then
      # Ensure we are making the only entry in the profile.d script
      [ -f "$rc_filename" ] && $dry rm -f "$rc_filename"
      if [ -z "$dry" ]; then
         tmp_sudoers=$(mktemp)
         echo -n "$sudo_update" > "$tmp_sudoers"
         if visudo -cf "$tmp_sudoers"; then
            install -m 440 "$tmp_sudoers" /etc/sudoers.d/10-ncurses
         else
            echo "Generated sudoers snippet failed validation; not installing." >&2
         fi
         rm -f "$tmp_sudoers"
      fi
   fi
   if [[ -z "$dry" ]]; then
      echo '' >> "$rc_filename"
      echo -n "$env_update" >> "$rc_filename"
      [[ "$system" == true ]] && chmod "$mode" "$rc_filename"
   fi
   echo "|   ---------------------------   WARNING ! --------------------------------   |"
   echo "$msg"
   echo "|   ---------------------------   WARNING ! --------------------------------   |"
fi

echo "|              Please do FULL FWD rebuild to activate the changes.             |"
echo "+------------------------------------------------------------------------------+"

# back to the starting directory
$dry popd > /dev/null

# On a successful build, clean up the downloaded source artifacts. The extracted
# source tree is only disposable when -p copied the libraries elsewhere; otherwise
# NCURSES_FWD_STATIC points into it and it must be kept.
if [ "$make_rc" -eq 0 ]; then
   $dry rm -f ncurses_*.dsc ncurses_*.debian.tar.* ncurses_*.orig.tar.*
   [ -n "$target_dir" ] && $dry rm -rf ncurses-6.*
fi
