#!/bin/bash

if [[ $EUID -ne 0 ]];
then
    echo "Run as root"
    exit 1
fi

set -euo pipefail

# check we are connected, else we wait
counter=0
until ping -c 5 charge.re > /dev/null 2>&1
do
  ((counter+=1))
  if [[ $counter -eq 360 ]]
  then
    echo "waited for hours, still offline. exiting now"
    exit 1
  fi
  sleep 60
done

readonly name="rossinienergy"

function update() {
    apt update -y -o Dir::Etc::sourcelist="sources.list.d/${name}.list" \
        -o Dir::Etc::sourceparts="-" -o APT::Get::List-Cleanup="0"
}

function upgrade() {
    apt -y -o Dir::Etc::sourcelist="sources.list.d/${name}.list" \
        -o Dir::Etc::sourceparts="-" -o Dpkg::Options::="--force-confdef" \
        -o Dpkg::Options::="--force-confold" -o Dpkg::Options::="--force-overwrite" upgrade
}

function reconfigure() {
    dpkg --configure -a
    upgrade
}

readonly lockfile=/tmp/update.lock

function cleanup() {
    rm "$lockfile"
}

function verify_lock() {
  find /tmp/ -mmin +720 -name 'update.lock' -delete
  if [[ -f $lockfile ]]
    then
      echo 'temp lock file from another update found, exiting now.'
      exit 1
    else
      echo 'updating...'
  fi
}

trap cleanup EXIT SIGINT
verify_lock
touch "$lockfile"
update
upgrade || reconfigure