#!/bin/bash

if [ ! -z "$(lsof /var/lib/dpkg/lock 2>/dev/null | grep '/var/lib/dpkg/lock')" ]; then
    exit 100
fi

# Possible arguments: lodraw, loimpress, lobase, lomath

if [ $# -gt 0 ]; then
  for ARG in "$@"; do
    #echo "$ARG"
    if [ "$ARG" == 'lodraw' ]; then
      PCK="$PCK libreoffice-draw"
    fi
    if [ "$ARG" == 'loimpress' ]; then
      PCK="$PCK libreoffice-impress"
    fi
    if [ "$ARG" == 'lobase' ]; then
      PCK="$PCK libreoffice-base"
    fi
    if [ "$ARG" == 'lomath' ]; then
      PCK="$PCK libreoffice-math"
    fi
  done
fi

if [ -z "$PCK" ]; then
  exit
fi

# ===============================================================

# --force-yes is deprecated in stretch
FORCE='--force-yes'
. /etc/lsb-release
if [[ -z "$DISTRIB_RELEASE" ]] || [ "$DISTRIB_RELEASE" -gt 8 ]; then
  FORCE='--allow-downgrades --allow-remove-essential --allow-change-held-packages'
fi

if [ ! -e /tmp/update-state ]; then
    apt-get update
    touch /tmp/update-state
fi

export DEBIAN_FRONTEND=gnome
echo
while IFS=' ' read -ra PS; do
  for P in "${PS[@]}"; do
    echo "Start installing: $P"
    apt-get install $BP --assume-yes -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold $FORCE $P
  done
done <<< "$PCK"
echo "Done"
