#! /usr/bin/env bash

# This is a simple wrapper for pacman to install packages at userspace.
# Everytime you execute this wrapper it will create ~/.local/var/pkglist.
# This dir is need to dump files which package is installed and which files are extracted to ~/.local/
# With the -i argument you install packages like:
# $ u8-pacman -i zola
# This will download zola from the repository and pipe the tar.zst to extract the files into ~/.local/
# also all exracted files will be documented at ~/.local/var/pkglist/zola.lst
# This wrapper need this file, to list installed packages, update all packages or remove the files.
#
# With the -l option you list all packages which are installed via this wrapper by list all files from ~/.local/bin/var/pkglist/
#
# The remove option -r $PACKAGENME will read the extracted files from ~/.local/bin/var/pkglist/$PACKAGENAME.lst and remove all this files.
# Also it will remove it self
#
# The -u option will read all ~/.local/bin/var/pkglist/*.lst files to gether the installed packages and reinstall them with the current package from the repository.

PACKAGE=$2
mkdir -p ~/.local/var/pkglist

usage()
{
cat <<EOF
Usage: $(basename $0) [options]
Options:
  -h               show this help page
  -i PACKAGENAME   install package
  -l               list installed packages
  -r PACKAGENAME   remove packagename
  -u               update all installed packages

EOF
}

while [ "$1" ]; do
  case "$1" in
    -i)
      shift
      source="install"
      ;;
    -r)
      shift
      source="remove"
      ;;
    -u)
      shift
      source="update"
      ;;
    -l)
      shift
      source="list"
      ;;
    -h)
      usage
      exit 0
      ;;
    *)
      echo "see -h for usage"
      exit 1
      ;;
  esac
  shift
done

function install() {
  curl -L $(pacman -Swpdd $1) -o - | tar --exclude='.*' --zstd -xvf - -C ~/.local/
  curl -s -L $(pacman -Swpdd $1) -o - | tar --zstd --exclude='.*' -tf - | grep -v '/$' > ~/.local/var/pkglist/$1.lst
  echo $1 is installed at $HOME/.local/
}

function remove() {
  while read files; do rm ~/.local/$files; done < ~/.local/var/pkglist/$1.lst
  rm ~/.local/var/pkglist/$1.lst
  echo removed files from $HOME/.local/ and $HOME/var/pkglist/$1.lst
}

function update() {
  while read list; do install $list; done < <(ls ~/.local/var/pkglist/*.lst | awk -F "/" '{print $NF}' | sed 's/\.lst//g')
}

function list() {
  ls ~/.local/var/pkglist/*.lst | awk -F "/" '{print $NF}' | sed 's/\.lst//g'
}

if [[ "$source" == "install" ]]; then
    if [ -z "$PACKAGE" ]; then
        echo "see -h for usage"
        exit 1
    fi
    install $PACKAGE
elif [[ "$source" == "remove" ]]; then
    if [ -z "$PACKAGE" ]; then
        echo "see -h for usage"
        exit 1
    fi
    remove $PACKAGE
elif [[ "$source" == "list" ]]; then
    if [ -z "$( ls -A ~/.local/var/pkglist )" ]; then
       exit 1
    fi
    list
elif [[ "$source" == "update" ]]; then
    update
elif [[ -z "$source" ]]; then
    echo "see -h for usage"
fi