#! /bin/bash
#--------------------------------------------------------------------------------------------------------
# Name: Pearl Featured Software Installer
# Authors: Misko_2083, Jerry Bezencon, gerito1, Johnathan "ShaggyTwoDope" Jenkins
# Authors: Misko_2083, Jerry Bezencon, gerito1
# Authors: Scott Vandergrift <scottvandergrift@gmail.com>
# Website: https://www.pearllinux.com
#--------------------------------------------------------------------------------------------------------

# Ensure multi-language support
export LANG=C

# Kill off any package managers that may be running
if [ "$(pidof synaptic)" ] 
then
   sudo killall -9 synaptic
fi

if [ ! -z "$(pgrep gdebi-gtk)" ]
then
   killall -9 gdebi-gtk
fi

# Set up log facilities
# Example output: [02/06/15 20:03:12] message input
LOGFILE=/var/log/pearl-software.log
log(){
    message="$@"
    echo '['$(date +%D\ %H:%M:%S)'] '$message >>$LOGFILE
}

# Log last activities to retrieve errors
TMP_LOG=/tmp/pearl-software.log

# Check if apt-cache was built and ask for update if needed
prepare(){
  if zenity --question --title="Update Sources" --window-icon=$ic --width=600 --text="We will now update your software sources.\n\nClick Yes to continue or No to abort."; then
    TOTALREPOS=$(cat /etc/apt/sources.list.d/official-package-repositories.list | grep '^deb' -c) # Total of repositories registered, this is approximated
    sudo apt-get update 2>&1 | awk -v total=$TOTALREPOS '/^Ign|^ Get/{count++;$1=""} FNR { if (total != 0){percentage=int (100*count/total);print (percentage < 90?percentage:90),"\n#",$0 }; fflush(stdout)}' \
      | zenity --progress --text="Updating package lists..." --window-icon=$ic --title="Updating Software Sources - please wait..." --percentage=0 --auto-close --width=800
    if [ "${PIPESTATUS[0]}" -ne "0" ]; then
      zenity --error --title="Error" --text="Updating sources has failed.\n\nRefer to /var/log/pearl-software.log\n\nfor more information."
      log "ERROR: Updating sources has failed."
      exit 0
    fi
    log "INFO: Software sources were updated."
  else
    log "INFO: The updating of packages was cancelled by the user"
    exit
  fi
}

# Set app icon variable
APPICON=/usr/share/pearlsoftware/appicons

#--------------------------------------------------------------------------------------------------------
# soft_list is the list of package aliases to check/install/remove
# Consist in a list describing aspect for every package
# package_alias=( "element 0" "element 1" "element 2" "element 3" "element 4" "element 5" "element 6")
# element 0: TRUE\FALSE for being selected
# element 1: The Application name ie: Google Chrome, iDevices Manager
# element 2: The category which belongs to (one only) ie:  Internet, Multimedia
# element 3: Status of the package ie: Installed, Not Installed
# element 4: Description of the package ie: "Easily locate files and folders in your computer", "Clementine is a modern music player and library organizer"
# element 5: List of packages needed to provide the application ie: "aisleriot gnome-mahjongg gnome-mines gnome-hearts"
# element 6: List of additional packages (this is optional) ie: libavformat-extra-54
#--------------------------------------------------------------------------------------------------------
soft_list=(appgrid
  audacious
  audacity
  ardour
  calibre
  chromiumbr
  clementine
  dropbox
  epiphany
  etherape
  codecs
  fluidsoundfontgs
  gamespack
  gdebi
  guvcview
  guitarix
  handbrake
  inkscape
  imessenger
  k3b
  kdenlive
  kodi
  libreoffice
  lingot
  lmms
  mixxx
  mudita24
  obsstudio
  passmgr
  pinta
  playonlinux
  puddletag
  samba
  rakarrack 
  remote
  rhythmbox
  supertux
  smplayer
  torrent
  videoedit
  vbox
  weather
  winestable
  winestablei386
  winehqstable
  webmin)

appgrid=("$APPICON/appgrid.png" "AppGrid" "System" "" "Superfast Software Installation Interface" "appgrid" "" )
audacious=("$APPICON/audacity.png" "Audacious" "Multimedia" "" "Linux standard for Audio Editing" "audacious" "" )
abiword=("$APPICON/abiword.png" "Abiword" "Multimedia" "" "Microsoft Word Type Software" "abiword" "" )
audacity=("$APPICON/audacity.png" "Audacity" "Multimedia" "" "Linux standard for Audio Editing" "audacity" "" )
ardour=("$APPICON/ardour.png" "Ardour" "Multimedia" "" "The 2nd best Multitrack hard disk recording software for Linux" "ardour" "" )
calibre=("$APPICON/calibre.png" "Calibre" "Office" "" "A free and open source e-book library management application" "calibre" "" )
chromiumbr=("$APPICON/chromium.png" "Chromium Web Browser" "Internet" "" "Open-source alternative to the Google Chrome web browser" "chromium-browser" "" )
clementine=("$APPICON/clementine.png" "Audio Player" "Multimedia" "" "Play and Manage your Music files" "clementine" "" )
dropbox=("$APPICON/dropbox.png" "Audio Player" "Internet" "" "Play and Manage your files" "dropbox" "" )
epiphany=("$APPICON/pearl-webbrowser.png" "Pearl-WebBrowser" "Internet" "" "Pearl Epiphany Web Browser" "epiphany-browser epiphany-browser-data" "" )
etherape=("$APPICON/etherape.png" "Etherape" "Internet" "" "Live Network Monitoring Solution" "etherape" "" )
codecs=("$APPICON/codecs.png" "Pearl Media Codecs" "Multimedia" "" "Additional codecs and useful file formats" "pearl-meta-codecs" "" )
gdebi=("$APPICON/gdebi.png" "Gdebi" "System" "" "Install debian packages with this GUI" "gdebi" "" )
guvcview=("$APPICON/guvcview.png" "Webcam Software" "Internet" "" "Guvcview, webcam software for your computer" "guvcview" "" )
guitarix=("$APPICON/guitarix.png" "Guitarix" "Multimedia" "" "Guitar Effects" "guitarix" "" )
fluidsoundfontgs=("$APPICON/fluidsoundfontgs.png" "FluidSoundFontGs" "Multimedia" "" "MIDI Soundfonts" "fluid-soundfont-gs" "" )
gamespack=("$APPICON/gamespack.png" "Games Pack" "Games" "" "Provides with Solitaire, Mahjongg, Mines and Hearts games" "aisleriot gnome-mahjongg gnome-mines gnome-hearts" "" )
handbrake=("$APPICON/handbrake.png" "HandBrake" "Multimedia" "" "Great Video Codecs Converter" "handbrake" "" )
inkscape=("$APPICON/inkscape.png" "InkScape" "Graphics" "" "Great for working on svg files" "inkscape" "" )
k3b=("$APPICON/k3b.png" "k3b" "Multimedia" "" "DVD Burning" "k3b" "" )
kdenlive=("$APPICON/kdenlive.png" "Kdenlive" "Multimedia" "" "The Best Video Editor on Linux" "kdenlive" "" )
imessenger=("$APPICON/pidgin.png" "Instant Messenger" "Internet" "" "Pidgin, a multi-protocol Instant Messenging client" "pidgin" "" )
kodi=("$APPICON/kodi.png" "Kodi" "Multimedia" "" "The Kodi Media Center (formerly known as XBMC)" "kodi" "" )
libreoffice=("$APPICON/libreoffice.png" "LibreOffice" "Office" "" "Full Microsoft Office Type Suite" "libreoffice" "" )
lingot=("$APPICON/lingot.png" "Lingot" "Multimedia" "" "Guitar Tuner" "lingot" "" )
lmms=("$APPICON/lmms.png" "Lmms" "Multimedia" "" "MIDI player and recording Software" "lmms" "" )
mixxx=("$APPICON/mixxx.png" "DJ Interface" "Multimedia" "" "Mixxx can play and record as you dj the audio" "mixxx" "")
mudita24=("$APPICON/mudita24.png" "Mudita24" "Multimedia" "" "An ALSA Mixer great for M Audio Delta Series" "mudita24" "")
obsstudio=("$APPICON/obs.png" "Screen Recorder" "Multimedia" "" "Most popular Screen Recording with live green screening" "obs-studio" "")
passmgr=("$APPICON/keepassx.png" "Password Manager" "Accessories" "" "KeePassX, an excellent password manager" "keepassx" "" )
pinta=("$APPICON/pinta.png" "Pinta" "Graphics" "" "An easy to use drawing program similar to Paint.Net" "pinta" "" )
playonlinux=("$APPICON/playonlinux.png" "PlayOnLinux" "Cross Platform" "" "Use numerous games and apps designed to run with Windows" "playonlinux" "" )
puddletag=("$APPICON/puddletag.png" "Puddletag" "Multimedia" "" "MP3 tagger" "puddletag" "" )
rakarrack=("$APPICON/rakarrack.png" "Rakarrack" "Multimedia" "" "A guitar Effects Processor" "rakarrack" "" )
remote=("$APPICON/remmina.png" "Remote Desktop Software" "Internet" "" "Remmina Remote Desktop Client for Windows (RDP) and VNC Servers" "remmina" "" )
rhythmbox=("$APPICON/rhythmbox.png" "Rhythmbox" "Multimedia" "" "Linux standard for Audio Editing" "rhythmbox" "" )
samba=("$APPICON/samba.png" "System-Config-Samba" "System" "" "Configure Shared Folders using Windows Networking" "system-config-samba" "" )
supertux=("$APPICON/supertux.png" "Supertux" "Games" "" "Supertux is a game similar to super mario world" "supertux" "" )
smplayer=("$APPICON/smplayer.png" "SMPlayer" "Multimedia" "" "Linux standard for Video Player" "smplayer" "" )
torrent=("$APPICON/transmission.png" "Torrent Software" "Internet" "" "Transmission Torrent client software" "transmission" "" )
videoedit=("$APPICON/openshot.png" "Video Editing Software" "Multimedia" "" "Openshot, a simple to use yet powerful video editor for linux" "openshot blender imagemagick" "")
vbox=("$APPICON/virtualbox.png" "VirtualBox" "System" "" "Install other operating systems like Windows from within Pearl Linux" "virtualbox" "" )
weather=("$APPICON/weather.png" "Weather Monitor" "System Tray" "" "A Weather Monitor Plugin for your tray" "xfce4-weather-plugin" "" )
winestable=("$APPICON/wine.png" "WineStable" "Cross Platform" "" "Use numerous games and apps designed to run with Windows" "wine-stable" "" )
winestablei386=("$APPICON/wine.png" "WineStablei386" "Cross Platform" "" "Use numerous games and apps designed to run with Windows" "wine-stable-i386" "" )
winehqstable=("$APPICON/wine.png" "WineHQStable" "Cross Platform" "" "Use numerous games and apps designed to run with Windows" "winehq-stable" "" )
webmin=("$APPICON/webmin.png" "Webmin Server Management" "System" "" "Easy system Management local or from the Internet" "webmin" "" )


get_pkg_status(){
  result="Installed"
  for PKG in  $@
  do
    TEST_PKG=(`apt-cache policy $PKG | grep "Installed:"`)
    if [ "${TEST_PKG[1]}" == "(none)" ];then
      result="Not Installed"
      break
    fi
  done
  read ${2} <<< $result
  unset result
  unset TEST_PKG
}

# Check for installed packages
check_installed(){
  for element in ${soft_list[*]}
  do
    current_pkg=$element[5]
    status=$element[3]
    get_pkg_status "${!current_pkg}" status # Get the status of the main package
    read ${element}"[3]" <<< $status        # Write the status in the package status
  done
}

install_pkgs(){
  declare -a pkg_arr=("${!1}")

  log "INFO: Installation of packages initiated: ${pkg_arr[@]}"
  sudo apt-get install -f --show-progress ${pkg_arr[@]} --force-yes -y 2>&1 | tee $TMP_LOG | awk ' BEGIN { FS=" "; total=1;end_download=0} /upgraded/ {total= $1 + $3;FS="[ :]" } /^Get:[[:digit:]]+/ {printf "#Downloading %s %s %s\n",$7,$(NF-1),$NF;print int(($2 - 1) * 100 / total); fflush(stdout)} /^\(Reading / {if (end_download==0){print 100;fflush(stdout);end_download=1}} /^(Preparing|Unpacking|Selecting|Processing|Setting|Download)/ {print "#", $0; fflush(stdout)}  /^Progress/ {print  match($0, /([0-9]+)/, arr); if(arr[1] != "") print arr[1] ; fflush(stdout)}' \
   | ( zenity --window-icon=$ic --progress --width=600 --text="Downloading package(s)...\nThis may take a while." --title="Downloading - please wait..." --percentage=0 --auto-close ; zenity --progress --window-icon=$ic --width=820 --text="Installing and configuring packages...\nThis may take a while." --title="Installing - please wait..." --auto-close )
  if [ "${PIPESTATUS[0]}" -ne "0" ]; then
    err_msg=$(awk '/^E:/{$1=""; print $0}' $TMP_LOG | tail -n 1)
    log "ERROR:$err_msg"
    zenity --error --title="Error" --text="Error\n$err_msg"
    return
  else
    zenity --info --title="Install Complete" --text="The package(s) installed successfully."
    log "INFO: Installation was a success."
  fi
}

remove_pkgs(){
  declare -a pkg_arr=("${!1}")

  log "INFO: Removal of packages initiated: ${pkg_arr[@]}"
  sudo apt-get remove -f ${pkg_arr[@]} --force-yes -y 2>&1 | tee $TMP_LOG | awk ' BEGIN { FS=" "; total=0; pkg=0}  /upgraded/ {total=$6 } /^Removing/ {print "#", $0;pkg+=1;print int((pkg - 1) * 100 / total); fflush(stdout)}' \
    | zenity --progress --window-icon=$ic --width=600 --text="Removing package(s)...\nThis may take a while." --title="Removing Software - please wait..." --percentage=0 --auto-close
  if [ "${PIPESTATUS[0]}" -ne "0" ]; then
    err_msg=$(awk '/^E:/{$1=""; print $0}' $TMP_LOG | tail -n 1)
    log "ERROR:$err_msg"
    zenity --error --title="Error" --text="Error\n$err_msg"
    return
  else
    zenity --info --title="Removal Complete" --text="The package(s) uninstalled successfully."
    log "INFO: Removal was a success."
  fi
}

# The installation menu
install_menu(){
  check_installed
  ic="/usr/share/icons/zenity-llcc.png"
  selection=$(for element in ${soft_list[*]}
    do
      row=$element[@]                          #grab the whole row
      printf  '%s\n' "${!row}"                 #print every element in the row separated with a newline
    done | zenity --window-icon="$ic" --list --imagelist --multiple --width=920 --height=760 --print-column=2,6,7 --separator="| " --column="Select" --column="Name" --column="Category" --column="Status" \
      --column="Description" --column="Packages" --column="Optional Packages" --text="Select the program you wish to install, then click the Install button. Sort Categories by clicking on the column.\nYou can select multiple programs to install by holding down the Ctrl or Shift keys." \
      --title="Install Additional Software" --ok-label="Install" --hide-column=6,7 )

  # If Cancel is clicked then return to main loop
  if [ "${PIPESTATUS[0]}" -ne "0" ]; then
    return
  fi

  # Check if anything is selected
  echo $selection | grep '[a-zA-Z0-9]'
  if [ "${PIPESTATUS[1]}" -ne "0" ]; then
    zenity --info --title='Install Additional Software' --text='Nothing was selected for installation.'
    return
  fi

  # Split selection
  OIFS=$IFS
  IFS='|'
  selection_array=($selection)
  PKGS_NAMES=""
  PKGS=""
  for ((i=0; i<${#selection_array[@]}; ++i));
  do
    if (( i % 3 == 0 )); then
      PKGS_NAMES=$PKGS_NAMES${selection_array[$i]}"\n"
      continue
    fi
    PKGS=$PKGS${selection_array[$i]}" "
  done
  IFS=$OIFS

  zenity --question --title="Install Software" --window-icon="${ic}" --text="The following software is selected for installation:\n\n $PKGS_NAMES \n Do you want to proceed?"
  if [ "$?" -eq "0" ]; then
    install_pkgs PKGS[@]
  else
    return
  fi
}

# The installation menu
remove_menu(){

  check_installed
  ic="/usr/share/icons/zenity-llcc.png"

  selection=$(for element in ${soft_list[*]}
    do
      pkg_status=$element[3]

      #Only list Installed applications
      if [ "${!pkg_status}" == "Not Installed" ]; then
        continue;
      fi
      row=$element[@]                          #grab the whole row
      printf  '%s\n' "${!row}"                 #print every element in the row separated with a newline
    done | zenity --window-icon="$ic" --list --imagelist --multiple --width=920 --height=760 --print-column=2,6 --separator="| " --column="Select" --column="Name" --column="Category" --column="Status" \
      --column="Description" --column="Packages" --column="Optional Packages" --text="Select the program you wish to remove, then click the Remove button. Sort Categories by clicking on the column.\nYou can select multiple programs to remove by holding down the Ctrl or Shift keys." \
      --title="Remove Additional Software" --ok-label="Remove" --hide-column=6,7 )

  # If Cancel is clicked then return to main loop
  if [ "${PIPESTATUS[0]}" -ne "0" ]; then
    return
  fi

  # Check if anything is selected
  echo $selection | grep '[a-zA-Z0-9]'
  if [ "${PIPESTATUS[1]}" -ne "0" ]; then
    zenity --info --title='Remove Software' --text='Nothing was selected for removal.'
    return
  fi

  # Split selection
  OIFS=$IFS
  IFS='|'
  selection_array=($selection)
  PKGS_NAMES=""
  PKGS=""
  for ((i=0; i<${#selection_array[@]}; ++i));
  do
    if (( i % 2 == 0 )); then
      PKGS_NAMES=$PKGS_NAMES${selection_array[$i]}"\n"
      continue
    fi
    PKGS=$PKGS${selection_array[$i]}" "
  done
  IFS=$OIFS
  zenity --question --title="Remove Software" --window-icon="${ic}" --text="The following software is selected for removal:\n\n $PKGS_NAMES \n Do you want to proceed?"
  if [ "$?" -eq "0" ]; then
    remove_pkgs PKGS[@]
  else
    return
  fi
}

# We begin here
prepare
pkg_manager_check
# The main loop
while (true); do
  TASK=$(zenity --width=450 --height=380 --list --radiolist --text="Select a task:" \
    --title="Pearl Featured Software" --column="Select" --column="Task" --column="Code Task" --hide-column=3 \
    --print-column=3 --cancel-label="Quit" TRUE "Install Software" 1 FALSE "Remove Software" 2 FALSE "Exit" 3)
  if [ "${PIPESTATUS[0]}" -ne "0" ]; then
    exit 0
  elif [ -n "${TASK}" ];then
    case $TASK in
      "1")
        install_menu
        ;;
      "2")
        remove_menu
        ;;
      "3")
        exit 0
        ;;
    esac
  fi
done

exit 0
