#!/bin/bash
# Copyright Jean-Philippe Guillemin <h1p8r10n@yandex.com>. 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. Please take a look at http://www.gnu.org/copyleft/gpl.htm
#
# Zenpkg is a tool to easily install or upgrade packages from the desktop.
#

# Check for arguments
if [ $# -eq 0 ]; then
  yad --error \
    --title="Error" \
    --text="Usage : zenpkg [package1] [package2] ... [packageN]" \
    --button="Close:0" \
    --window-icon="netpkg" \
    --width=400
  exit 1
fi

# Filter valid package files (.tgz, .tbz, .tlz, .txz)
list=()
for path in "$@"; do
  [ -f "$path" ] || continue
  [[ "$path" =~ \.t[glx]z$ ]] || continue
  list+=("$path")
done

# How many packages do we have to install
pkgtotalcount=${#list[@]}
if [ $pkgtotalcount -eq 0 ]; then
  yad --error \
    --title="Error" \
    --text="No valid package to process" \
    --button="Close:0" \
    --window-icon="netpkg" \
    --width=300
  exit 1
fi

step=$((100 / pkgtotalcount))
[ $step -eq 0 ] && step=1
pkgcount=0

(
  for path in "${list[@]}"; do
    package="$(basename "$path")"

    progress=$((pkgcount * step))
    echo "$progress"
    echo "# Processing: $package"

    # Push progress bar midway
    progress=$((progress + step / 2))
    echo "$progress"

    # Install/upgrade package
    /sbin/upgradepkg --install-new --reinstall "$path" >/dev/null 2>&1

    progress=$((progress + step / 2))
    echo "$progress"
    sleep 1

    pkgcount=$((pkgcount + 1))
  done
  echo 100
  echo "# Processing complete!"
  sleep 1
) | yad --progress \
  --title="Zenpkg" \
  --text="Processing $pkgtotalcount package(s)..." \
  --percentage=0 \
  --auto-close \
  --window-icon="netpkg" \
  --center \
  --width=450
