#!/bin/bash

astra_update() {
  show_greetings() {
    echo " ";
    echo " Utility to update and upgrage packages for Astra Linux";
    echo " Copyright (c) 2020-2023 Alexey Kuryakin kouriakine@mail.ru";
    echo " Version: 20230117";
    echo "";
  };
  show_title() {
    echo " ";
    echo " $*";
    echo " ";
  };
  confirm () {
   local ans;
   echo -ne "$1";
   if read -n 1 -t 60 -p " (y/n): " ans; then
    [ "$ans" = "y" ] && return 0;
    echo -e "\nSkipped.";
    return 1;
   else
    echo -e "\nTimeout!";
    echo -e "\nSkipped.";
    return 2;
   fi;
  };
  press_any_key() {
   clear_line () {
    printf "\r%40s\r" " ";
   };
   [ -n "$*" ] && echo "$*";
   read -n 1 -p "Press any key to continue... ";
   clear_line;
  };
  backward_counting() {
   clear_line () {
    printf "\r%40s\r" " ";
   };
   print_counting () {
    printf "\rWait %-35d\r" "$1";
   };
   local n=$1;
   print_counting $n;
   for i in $(seq 0 1 $n); do
    read -n 1 -t 1 && clear_line && return 0;
    n=$(expr $n - 1);
    print_counting $n;
    [ "$n" == "0" ] && clear_line && return 0;
   done;
  };
  show_run() {
    local title="$1";
    shift;
    show_title "$title";
    echo "Run: $*";
    $*;
  };
  skip_run() {
    local title="$1";
    shift;
    show_title "$title";
    echo "Skip: $*";
  };
  install_packages() {
    show_run "Update packages..."                 sudo apt update;
    confirm  "Upgrage packages..."             && sudo apt dist-upgrade;
  };
  clear;
  show_greetings;
  install_packages;
  show_title "Done";
};
astra_update;
