#!/bin/bash
#
#  This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as
#  published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
###
# Make a new folder for the results
mkdir -p "$HOME/releasecompare" && cd "$HOME/releasecompare" || exit 1
###
# URL help for the release sources
_release_url_help() {
  echo ""
  echo -e "For Manjaro releases:"
  echo -e "Please go to \e[7mhttps://sourceforge.net/projects/manjarolinux/files/\e[0m"
  echo -e "\e[1m-> Edition\e[0m \e[1m-> Release_Number\e[0m \e[1m-> *.iso.pkgs\e[0m and copy the URL."
  echo -e ""
  echo -e "For Arch releases (archiso profiles, one package name per line):"
  # Short URLs, so a pasted link is not split over lines
  echo -e "\e[7mhttps://github.com/archlinux/archiso/raw/master/configs/releng/packages.x86_64\e[0m"
  echo -e "\e[7mhttps://github.com/archlinux/archiso/raw/master/configs/baseline/packages.x86_64\e[0m"
  echo ""
  echo -e "  1) Copy/Paste the URL to *pkgs* and press ENTER"
  echo -e "  0) Quit"
}

# Every question reads a whole line; an empty answer is asked again
_read_choice() { # <prompt> [hint on an empty answer] -> sets $answer, rc 1 on EOF
  local hint="${2:-No choice yet - type the number and press ENTER.}"
  local empty=0
  answer=""
  while true; do
    printf '%s' "$1"
    if ! read -r answer; then
      # A last line without a trailing newline still carries the answer
      [ -n "$answer" ] && return 0
      answer=""
      return 1
    fi
    if [ -n "$answer" ]; then
      return 0
    fi
    echo "$hint"
    if ! [ -t 0 ]; then
      empty=$((empty + 1))
      [ "$empty" -lt 3 ] || return 1
    fi
  done
}

# A [y]es or [N]o question, EOF is refused
_ask_yes_no() { # <prompt> -> sets $answer, rc 1 on EOF
  printf '%s' "$1"
  answer=""
  if ! read -r answer; then
    [ -n "$answer" ] && { answer=$(printf '%s' "$answer" | tr '[:upper:]' '[:lower:]'); return 0; }
    return 1
  fi
  answer=$(printf '%s' "$answer" | tr '[:upper:]' '[:lower:]')
  return 0
}

_fetch_and_diff() {
  echo -e "Paste the URL of the release package list and press ENTER."
  if ! _read_choice 'URL: ' "Empty input. Paste a URL and press ENTER."; then
    echo "No input."
    return 1
  fi
  uservar="$answer"

  # Only a download page carries the trailing /download
  case "$uservar" in
  */download) uservar="${uservar%/download}" ;;
  esac

  # The download is bounded and `--` keeps a dash-leading input out of the options
  wget -q --tries=2 --timeout=30 -O pkgs.txt -- "$uservar"
  if ! [ -s pkgs.txt ]; then
    echo -e "\e[41m Nothing was downloaded. Check the URL. \e[0m"
    rm -f pkgs.txt
    exit 1
  fi
  # One package name per line is what this file has to be
  if grep -qiE '<!doctype html|<html[[:space:]>]' pkgs.txt; then
    echo -e "\e[41m That URL is a web page, not a package list. \e[0m"
    echo -e " Open the release page, follow it to the *.pkgs file, and copy the URL of that file."
    rm -f pkgs.txt
    exit 1
  fi

  # generate list of installed packages
  pacman -Q >pacman.txt

  # final Comparison
  cut -d' ' -f1 pkgs.txt | sort -u >comp1.txt
  cut -d' ' -f1 pacman.txt | sort -u >comp2.txt
  echo -e " Comparing $(wc -l <comp2.txt) installed packages with $(wc -l <comp1.txt) packages from the release list."
  comm -13 comp2.txt comp1.txt | tee release.txt >/dev/null     # Packages from Release which are not installed local
  comm -23 comp2.txt comp1.txt | tee userpkglist.txt >/dev/null # Packages installed by User
  echo -e " $(wc -l <release.txt) release packages are not installed, $(wc -l <userpkglist.txt) installed packages are not in the release list."

  # clean up
  rm -f pkgs.txt comp1.txt comp2.txt index.html path.txt

  _userreleasepkglist
  printf '\33[H\33[2J'
  echo ""
  echo -e "\e[7m The Results Were Saved To: \e[0m"
  echo -e "\e[1m $HOME/releasecompare \e[0m"
  echo ""
  _meld
}

_ask_and_diff() {
  # The help is printed inside the loop
  while true; do
    _release_url_help
    if ! _read_choice ""; then
      echo "No input, nothing was compared."
      return 0
    fi
    case "$answer" in
    1)
      _fetch_and_diff
      return 0
      ;;
    0 | q | Q)
      # clean up
      rm -f pkgs.txt comp1.txt comp2.txt index.html path.txt release.txt
      exit
      ;;
    *)
      echo "invalid option '$answer'"
      rm -f pkgs.txt comp1.txt comp2.txt index.html path.txt release.txt
      ;;
    esac
  done
}

# Custom URL to *pkgs*
_custom_URL() {
  printf '\33[H\33[2J'
  echo
  if [ -e "$HOME/releasecompare/release-removed-uninstalled.txt" ]; then # If file exists
    echo -e "\e[1m Do you want to remove any existing results? (Recommended) \e[0m"
    # No answer keeps the existing results
    if _ask_yes_no "Remove the existing results ([y]es or [N]o): "; then
      case "$answer" in
      y | yes)
        echo -e "\e[1m yes \e[0m"
        rm -rf "$HOME"/releasecompare/*
        ;;
      *)
        echo -e "\e[1m no \e[0m"
        ;;
      esac
    else
      echo -e "\e[1m no \e[0m"
    fi
  fi
  _ask_and_diff
}
# Open results in Meld
_meld() {
  if [ -e /usr/bin/meld ]; then # If file exists
    echo
    echo -e "\e[1m Do you want to view the results in Meld? \e[0m"
    if ! _ask_yes_no "Open the results in Meld ([y]es or [N]o): "; then
      echo -e "\e[1m no \e[0m"
      return 0
    fi
    case "$answer" in
    y | yes)
      echo -e "\e[1m yes \e[0m"
      # Only the result files that exist are handed to meld
      results=()
      for f in release-removed-uninstalled.txt *release.txt; do
        [ -e "$f" ] && results+=("$f")
      done
      if [ "${#results[@]}" -eq 0 ]; then
        echo -e "\e[41m No result files here, nothing to compare. \e[0m"
        return 1
      fi
      meld "${results[@]}"
      # Return, not exit: the install runs afterwards
      return 0
      ;;
    *) echo -e "\e[1m no \e[0m" ;;
    esac
  fi
}
###
# Create Release pkglist without packages that were uninstalled by the User
_userreleasepkglist() {
  log=${BMENU_PACMAN_LOG:-/var/log/pacman.log}
  if ! [ -r "$log" ]; then
    echo "No readable $log, so the uninstall list stays empty."
    : >removed.txt
  else
    # Only pacman's own removal records count: [ALPM] removed <name> (<version>)
    record='[[]ALPM[]] removed [^ ]+ \([^()]+\)'
    grep -oE "$record" "$log" | sed -E 's/.* removed ([^ ]+) \(.*/\1/' | sort -u >removed.txt
    skipped=$(grep 'removed' "$log" | grep -vcE "$record")
    if [ "$skipped" -gt 0 ]; then
      echo "Skipped $skipped pacman.log lines that mention a removal but are not a removal record (scriptlet output and similar)."
    fi
  fi
  if ! ls *release.txt >/dev/null 2>&1; then
    echo "No release list found, nothing to compare against."
    rm -f removed.txt
    return 1
  fi
  # Sorted, so the comparison sees every common line
  cat ./*release.txt | cut -d' ' -f1 | sort -u >install.txt
  comm -13 removed.txt install.txt >release-removed-uninstalled.txt
  echo -e " $(wc -l <install.txt) release packages, $(wc -l <removed.txt) recorded uninstalls, $(wc -l <release-removed-uninstalled.txt) left for the install list."
  rm -rf 4.txt 5.txt 6.txt comp2.txt ergebnis.txt final.txt install.txt newdiffreverse.txt outfile.txt pacman.txt removed.txt

}
###
# One install run over a list file, read from stdin
# The count is printed first
_install_from() { # <list file>
  local file="$1" n
  if [ ! -s "$file" ]; then
    echo "No packages in $file, nothing was installed."
    return 1
  fi
  n=$(grep -c '[^[:space:]]' "$file")
  echo ""
  echo -e "\e[7m Starting installation of $n packages from $file \e[0m"
  echo ""
  sudo pacman -Syu - <"$file"
}

###
# Check if local release.txt file exists for possible installation and to avoid running a new comparison which would overwrite user changes
_installcheck() {
  printf '\33[H\33[2J'
  echo ""
  local keep
  # The release lists are collected in an array
  rfiles=()
  for f in ./*release.txt; do
    [ -f "$f" ] && rfiles+=("$f")
  done
  if [ "${#rfiles[@]}" -gt 0 ]; then
    cat "${rfiles[@]}" | cut -d' ' -f1 | sort -u >install.txt
    while true; do
      echo ""
      echo -e "\e[7m A existing comparison was found! Please choose what to do! \e[0m"
      echo ""
      echo "  1) Install from *release.txt"
      echo "  2) Install from release-removed-uninstalled.txt"
      echo "  3) Install from *release.txt after a new Comparison"
      echo "  4) Install from release-removed-uninstalled.txt after a new Comparison"
      echo "  0) Quit"
      if ! _read_choice ""; then
        echo "No input, nothing was installed."
        rm -f install.txt
        return 0
      fi
      # The answer is kept in `keep`, not in `choice`
      keep="$answer"
      case "$keep" in
      1)
        _install_from install.txt
        rm -f install.txt
        return 0
        ;;
      2)
        _install_from release-removed-uninstalled.txt
        rm -f install.txt
        return 0
        ;;
      3 | 4)
        rm -f install.txt ./*release.txt userpkglist.txt release-removed-uninstalled.txt
        _custom_URL
        if [ "$keep" == "3" ]; then
          rfiles=()
          for f in ./*release.txt; do
            [ -f "$f" ] && rfiles+=("$f")
          done
          if [ "${#rfiles[@]}" -eq 0 ]; then
            echo "No release list was produced, nothing to install."
            return 1
          fi
          cat "${rfiles[@]}" | cut -d' ' -f1 | sort -u >install.txt
          _install_from install.txt
          rm -f install.txt
        else
          _install_from release-removed-uninstalled.txt
        fi
        return 0
        ;;
      0 | q | Q)
        rm -f install.txt
        exit
        ;;
      *)
        echo "invalid option '$keep'"
        ;;
      esac
    done
  else
    while true; do
      echo "  1) Install from *release.txt"
      echo "  2) Install from release-removed-uninstalled.txt"
      echo "  0) Quit"
      if ! _read_choice ""; then
        echo "No input, nothing was installed."
        return 0
      fi
      keep="$answer"
      case "$keep" in
      1)
        _custom_URL
        rfiles=()
        for f in ./*release.txt; do
          [ -f "$f" ] && rfiles+=("$f")
        done
        if [ "${#rfiles[@]}" -eq 0 ]; then
          echo "No release list was produced, nothing to install."
          return 1
        fi
        cat "${rfiles[@]}" | cut -d' ' -f1 | sort -u >install.txt
        _install_from install.txt
        rm -f install.txt
        return 0
        ;;
      2)
        _custom_URL
        _install_from release-removed-uninstalled.txt
        return 0
        ;;
      0 | q | Q)
        rm -rf install.txt
        exit
        ;;
      *)
        echo "invalid option '$keep'"
        ;;
      esac
    done

  fi
}
###
# install different packages Flag
if [ "$1" == "install" ]; then
  echo ""
  echo -e "\e[7m Installation Options \e[0m"
  _installcheck
  exit 0
fi
# Run the script without flags
_custom_URL
