#!/bin/sh

# opkg_list.sh
# 2022-07-03
# by Gernot WALZL

# Extends the opkg package manager with additional listing features,
# such as showing manually installed packages.
# Requires: diffutils

set -e

print_usage () {
  echo "Usage: $0 {added|added-manual|upgradable-added|upgradable-added-manual}"
}

list_added () {
  sed -n 's/^Package: //p' /rom/usr/lib/opkg/status \
    | sort > /tmp/opkg_packages_rom
  sed -n 's/^Package: //p' /usr/lib/opkg/status \
    | sort > /tmp/opkg_packages
  diff /tmp/opkg_packages_rom /tmp/opkg_packages \
    | sed -n 's/^> //p'
}

filter_auto () {
  while read PKG; do
    if ! grep -e '^Package: ' -e '^Auto-Installed: yes$' /usr/lib/opkg/status \
        | grep "^Package: $PKG\$" -A 1 \
        | grep -q '^Auto-Installed: yes$'; then
      echo "$PKG"
    fi
  done
}

list_added_manual () {
  list_added \
    | filter_auto
}

list_upgradable_added () {
  opkg list-upgradable \
    | cut -f 1 -d ' ' \
    | while read PKG; do
      if ! grep -q "^Package: $PKG\$" /rom/usr/lib/opkg/status; then
        echo "$PKG"
      fi
    done
}

list_upgradable_added_manual () {
  list_upgradable_added \
    | filter_auto
}

case "$1" in
 'added')
  list_added
  ;;
 'added-manual')
  list_added_manual
  ;;
 'upgradable-added')
  list_upgradable_added
  ;;
 'upgradable-added-manual')
  list_upgradable_added_manual
  ;;
 *)
  print_usage
esac