#!/bin/bash
set -e
set +o pipefail

PACKAGE_DIR="/tmp/os/update045Extract"
SERVICE_DIR="/usr/local/bin/identitysyncservices"
ROOT_WRITABLE=0
TEMP_FILES=()

cleanup() {
  exit_code=$?
  trap - EXIT
  if [ "${#TEMP_FILES[@]}" -gt 0 ]; then
    sudo rm -f -- "${TEMP_FILES[@]}" || true
  fi
  if [ "$ROOT_WRITABLE" -eq 1 ]; then
    echo "Returning root filesystem to read-only..."
    if ! sudo mount -o remount,ro /; then
      echo "Error: could not return root filesystem to read-only"
      if [ "$exit_code" -eq 0 ]; then
        exit_code=1
      fi
    fi
  fi
  echo "Installer exiting with code $exit_code"
  exit "$exit_code"
}
trap cleanup EXIT

install_file() {
  local source="$1"
  local target="$2"
  local temporary="${target}.update045.new"

  echo "Updating $target..."
  sudo mkdir -p "$(dirname "$target")"
  TEMP_FILES+=("$temporary")
  sudo install -o pi -g pi -m 775 "$source" "$temporary"
  sudo cmp -s "$source" "$temporary" || {
    echo "Error: staged copy verification failed: $target"
    exit 1
  }
  sudo mv -f "$temporary" "$target"
  sudo cmp -s "$source" "$target" || {
    echo "Error: installed file verification failed: $target"
    exit 1
  }
}

cd "$PACKAGE_DIR" || {
  echo "Error: $PACKAGE_DIR not found"
  exit 1
}

for source in tmp/os/phason.sh tmp/os/pbj/phason.sh \
  usr/local/bin/identitysyncservices/ph_alive_ping.py \
  usr/local/bin/identitysyncservices/ph_common.py; do
  if [ ! -f "$source" ]; then
    echo "Error: packaged file not found: $PACKAGE_DIR/$source"
    exit 1
  fi
done

echo "Checking packaged boot scripts..."
bash -n tmp/os/phason.sh
bash -n tmp/os/pbj/phason.sh
sudo mount -o remount,rw /
ROOT_WRITABLE=1

sudo systemctl stop ph_alive_ping.timer
sudo systemctl stop ph_alive_ping.service

install_file "$PACKAGE_DIR/tmp/os/phason.sh" /tmp/os/phason.sh
install_file "$PACKAGE_DIR/tmp/os/pbj/phason.sh" /tmp/os/pbj/phason.sh
install_file "$PACKAGE_DIR/usr/local/bin/identitysyncservices/ph_common.py" "$SERVICE_DIR/ph_common.py"
install_file "$PACKAGE_DIR/usr/local/bin/identitysyncservices/ph_alive_ping.py" "$SERVICE_DIR/ph_alive_ping.py"

sudo systemctl daemon-reload
sudo systemctl enable ph_alive_ping.timer
sudo systemctl restart ph_alive_ping.timer

if ! sudo systemctl is-enabled --quiet ph_alive_ping.timer; then
  echo "Error: ph_alive_ping.timer is not enabled"
  exit 1
fi

if ! sudo systemctl is-active --quiet ph_alive_ping.timer; then
  echo "Error: ph_alive_ping.timer is not active"
  sudo systemctl status ph_alive_ping.timer --no-pager || true
  exit 1
fi

if ! sudo systemctl start ph_alive_ping.service; then
  echo "Warning: alive ping failed; the timer will retry"
  sudo systemctl status ph_alive_ping.service --no-pager || true
fi

sudo touch /home/pi/update045
sudo chown pi:pi /home/pi/update045

echo "Installed update045 boot scripts and identity service files successfully."