#!/usr/bin/env bash
set -Eeuo pipefail

FLAG_DIR="/var/lib/nvidia-remove-gnome-software-once"
FLAG_FILE="${FLAG_DIR}/done"
TAG="nvidia-remove-gnome-software-once"

log() { logger -t "${TAG}" "$*"; }

# Already completed
if [[ -e "${FLAG_FILE}" ]]; then
  log "already completed; exiting"
  systemctl disable nvidia-remove-gnome-software-once.service || true
  exit 0
fi

# If gnome-software package is not installed, mark done, disable service and exit
if ! dpkg -s gnome-software >/dev/null 2>&1; then
  log "package gnome-software not installed; marking done"
  install -d -m 0700 "${FLAG_DIR}"
  echo "done" > "${FLAG_FILE}"
  chmod 0400 "${FLAG_FILE}"
  systemctl disable nvidia-remove-gnome-software-once.service || true
  exit 0
fi

# Try to remove once. If it fails, exit nonzero and let systemd retry at next boot.
log "attempting to remove packages"
if apt-get -y --auto-remove purge gnome-software gnome-contacts ; then
  install -d -m 0700 "${FLAG_DIR}"
  echo "done" > "${FLAG_FILE}"
  chmod 0400 "${FLAG_FILE}"
  log "remove completed; flag written"
  systemctl disable nvidia-remove-gnome-software-once.service || true
  exit 0
else
  log "apt-get purge failed; will retry on next boot"
  exit 1
fi
