#!/usr/bin/env bash
source $DOTFILES_PATH/bin/helpers/functions.sh

help() {
  printfe "%s\n" "green" "Usage: upgrade.sh [options]"
  printfe "%s\n" "green" "Options:"
  printfe "%s\n" "green" "  --ha, -H          Upgrade Home Manager packages."
  printfe "%s\n" "green" "  --ansible, -A     Upgrade Ansible packages."
  printfe "%s\n" "green" "  --ansible-verbose Upgrade Ansible packages with verbose output. (-vvv)"
  printfe "%s\n" "green" "  --full-speed, -F  Upgrade packages and use all available cores for compilation. (Default: 8 cores)"
  printfe "%s\n" "green" "  --help, -h        Display this help message."
  exit 0
}

while [[ "$#" -gt 0 ]]; do
  case $1 in
    --ha|-H) RUN_HA=true ;;
    --ansible|-A) RUN_ANSIBLE=true ;;
    --ansible-verbose) 
      RUN_ANSIBLE=true 
      ANSIBLE_VERBOSE=true ;;
    --full-speed|-F) FULL_SPEED=true ;;
    --help|-h) help ;;
    *) echo "Unknown parameter passed: $1";
    help ;;
  esac
  shift
done

if [[ -z "$RUN_HA" && -z "$RUN_ANSIBLE" ]]; then
  RUN_HA=true
  RUN_ANSIBLE=true
fi

# Check if --full-speed flag is passed, otherwise use  --cores 8 -j 1
if [[ "$FULL_SPEED" == true ]]; then
  CORES=$(nproc)
  JOBS=$(nproc)
else
  CORES=8
  JOBS=1
fi

printfe "%s\n" "cyan" "Limiting to $CORES cores with $JOBS jobs."

if [[ "$RUN_HA" == true ]]; then
  printfe "%s\n" "cyan" "Updating Home Manager flake..."
  cd $DOTFILES_PATH/config/home-manager && nix --extra-experimental-features nix-command --extra-experimental-features flakes flake update

  if command -v home-manager &> /dev/null; then
    printfe "%s\n" "cyan" "Cleaning old backup files..."
    rm -rf $HOME/.config/mimeapps.list.backup

    printfe "%s\n" "cyan" "Upgrading Home Manager packages..."
    cd $DOTFILES_PATH/config/home-manager && NIXPKGS_ALLOW_UNFREE=1 home-manager --extra-experimental-features nix-command --extra-experimental-features flakes switch -b backup --flake .#$HOSTNAME --impure --cores $CORES -j $JOBS

    if [[ $? -ne 0 ]]; then
      printfe "%s\n" "red" "Failed to upgrade Home Manager packages."
      exit 1
    fi
  else
    printfe "%s\n" "red" "Home Manager is not installed."
    exit 1
  fi
fi

if [[ "$RUN_ANSIBLE" == true ]]; then
  if ! command -v ansible-playbook &> /dev/null; then
    printfe "%s\n" "yellow" "Ansible is not installed, installing it with pipx..."
    pipx install --include-deps ansible ansible-lint

    if [[ $? -ne 0 ]]; then
      printfe "%s\n" "red" "Failed to install Ansible."
      exit 1
    fi
  fi
  
  printfe "%s\n" "cyan" "Running Ansible playbook..."
  cd $DOTFILES_PATH/config/ansible && ansible-playbook -i $DOTFILES_PATH/config/ansible/inventory.ini $DOTFILES_PATH/config/ansible/main.yml --extra-vars "hostname=$HOSTNAME" --extra-vars "ansible_user=$USER" --limit $HOSTNAME --ask-become-pass ${ANSIBLE_VERBOSE:+-vvv}
  
  if [[ $? -ne 0 ]]; then
    printfe "%s\n" "red" "Failed to upgrade Ansible packages."
    exit 1
  fi
fi
