#!/usr/bin/bash

#
# SPDX-License-Identifier: GPL-2.0
#
# Copyright (C) 2022 Eric Curtin <ecurtin@redhat.com>
#

set -e

print_help() {
  printf "%s\n%s\n" "Usage:" "  ostree-compliance-mode-helper enable"
}

confirm_continuation() {
  while true; do
    read -p "Are you sure you want to proceed? (yes/no) " yn

    case $yn in
      yes ) break;;
      no ) printf "exiting...\n";
           exit;;
      * ) printf "invalid response\n";;
    esac
  done
}

if [ "$1" != "enable" ]; then
  print_help
  exit 0
fi

if [ $EUID != 0 ]; then
  printf "This script must be run as root\n"
  exit 1
fi

if ! command -v ostree > /dev/null; then
  printf "ostree is not installed\n"
  exit 2
fi

if ! command -v rpm-ostree > /dev/null; then
  printf "rpm-ostree is not installed\n"
  exit 3
fi

num_of_deployments=$(rpm-ostree status --json | python -c 'import json,sys; print(len(json.load(sys.stdin)["deployments"]))')

for (( i = 0; i < $num_of_deployments; ++i )); do
  if [ $(rpm-ostree status --json | python -c "import json,sys; print(json.load(sys.stdin)[\"deployments\"][$i][\"booted\"])") == "True" ]; then
    break;
  fi
done

if [ "$i" -ge "$num_of_deployments" ]; then
  printf "No booted deployment found\n"
  exit 4
fi

currently_deployed_ref=$(rpm-ostree status --json | python -c "import json,sys; print(json.load(sys.stdin)[\"deployments\"][$i][\"origin\"])")
compliance_mode_ref=$(head -n1 /etc/ostree-compliance-mode.conf)

if [ "$currently_deployed_ref" != "$compliance_mode_ref" ]; then # 1st iteration
  printf "Enabling ostree-compliance-mode will leave the vehicle in an undrivable state removing proprietary data, this will also force a reboot\n"
  confirm_continuation
  ostree admin deploy $compliance_mode_ref
  reboot
else # 2nd iteration
  printf "Enabling ostree-compliance-mode will leave the vehicle in an undrivable state removing proprietary data\n"
  confirm_continuation
  # delete all refs except for the compliance-mode one and special ostree ones
  for i in $(ostree refs); do
    if [ "$i" != "^ostree" ] && [ "$i" != "$compliance_mode_ref" ]; then
      ostree refs --delete $i
    fi
  done

  rpm-ostree cleanup -pr # cleanup everything except booted deployment
  ostree prune --refs-only # now finally prune the other refs
  exec /bin/bash # grant root access at this point
fi

