#!/bin/bash

function alse_rsync_net_to_hdd()(
  function show_greetings() {
    echo " ";
    echo " Utility to copy Astra Linux repository mirror from NET to HDD";
    echo " Copyright (c) 2021-2023 Alexey Kuryakin kouriakine@mail.ru";
    echo " Version: 20230325";
    echo " ";
    echo "Login as «$(whoami)@$(hostname -s)».";  sudo pwd > /dev/null;
  };
  function show_title() {
    echo " ";
    echo " $*";
    echo " ";
  };
  function execute(){
    echo "";
    echo "$(date +%Y.%m.%d-%H:%M:%S) - Execute: $*";
    echo "";
    $*;
  };
  function execute_silent(){
    echo "";
    echo "$(date +%Y.%m.%d-%H:%M:%S) - Execute: $*";
    echo "";
    "$@" 1>/dev/null 2>/dev/null;
  };
  function ask_yesno(){
   local title="$1";
   local message="$2";
   [ -z "$(which zenity)" ] && { echo "Install zenity…"; sudo apt-get -y install zenity; };
   [ -n "$(which zenity)" ] && {
    sleep 1;
    message="<span face='PT Mono'>$message</span>";
    execute_silent zenity --title "$title" --question --text "$message" --timeout 180 --default-cancel --width 480 --modal;
    local result="$?"; local msg="no"; [ "$result" == "0" ] && msg="yes"; echo "Answer: $result ($msg)";
    return $result;
   };
   [ -n "$(which fly-dialog)" ] && { 
    sleep 1;
    execute_silent fly-dialog --title "$title" --yesno "$message";
    local result="$?"; local msg="no"; [ "$result" == "0" ] && msg="yes"; echo "Answer: $result ($msg)";
    return $result;
   };
   return 0;
  };
  function skip(){
   true;
  };
  function rsync_net_hdd(){
    local net=$1;
    local hdd=$2;
    local exclist=$3;
    echo "Source: $net";
    echo "Target: $hdd";
    local exclude=" ";
    [ -n "$(echo $exclist | grep alt)" ] && exclude="$exclude --exclude ALTLinux/";
    local options="--recursive --links --times --perms --devices --specials --verbose --stats --delete-before --prune-empty-dirs";
    [ -d $net ]                                    || { echo "Fails directory «$net»"; echo ""; return 1; };
    [ -d $hdd ]                                    || { echo "Fails directory «$hdd»"; echo ""; return 1; };
    [ "$(ls -1 $net/ 2>/dev/null | wc -l)" = "0" ] && { echo "Empty directory «$hdd»"; echo ""; return 1; };
    execute sudo rsync $options $exclude $net/ $hdd/;
    execute sudo chmod -cR a+r $hdd/;
    execute sudo du -sb $net/ $hdd/;
  };
  clear;
  show_greetings;
  ask_yesno "Confirmation required…" "Do You Want to:\n\nCopy (mirror) AstraLinuxCE Repository\nfrom NET ($1 server) to local HDD?\n\n<span size='xx-large' fgcolor='red'><b> NET =&gt; HDD </b></span>\n\n<span fgcolor='green'><b>Please Confirm Operation</b></span>." || return 1;
  local sourceserver=$1;
  rsync_net_hdd /mnt/ssh/$sourceserver/srv/public/mirror /srv/public/mirror "exclude:alt" "exclude-help:alt";
  show_title "Done";
);
alse_rsync_net_to_hdd simply;
