#!/bin/bash

## Copyright (C) 2012 - 2020 ENCRYPTED SUPPORT LP <adrelanos@riseup.net>
## See the file COPYING for copying conditions.

set -e
set -o pipefail
set -o errtrace

cleanup() {
   if [ -d "$temp_dir" ]; then
      rm --recursive --force "$temp_dir"
   fi
}

temp_dir="$(mktemp --directory)"
logfile="$temp_dir/log"

trap "cleanup" EXIT

apt_get_exit_code="0"

## Thanks to:
## dmw
## http://stackoverflow.com/a/26263980/2605155
## for the python way to create a pty.

python3.7 -c 'import pty, sys; pty.spawn(sys.argv[1:])' \
   | apt-get "$@" 2>&1 \
   | tee -a "$logfile" \
   || { apt_get_exit_code="$?"; true; };

if [ ! "$apt_get_exit_code" = "0" ]; then
   exit "$apt_get_exit_code"
fi

log="$(cat "$logfile")"

while read -r -d $'\n' line; do
   line_lower_case="${line,,}"
   first_two="${line_lower_case:0:2}"
   if [ "$first_two" = "e:" ]; then
      exit 125
   fi
   if [ "$first_two" = "w:" ]; then
      exit 125
   fi
done < <( echo "$log" )

exit "$apt_get_exit_code"
