#!/bin/bash
# - bof - #



<<'comment'
# -  - #
# - Ollama Backup - #
# -  - #
Origen & Destin /Data/Backup/OllamaModels

# -  - #
# - Bash - #
# - OllamaBackup.sh - #

# -  - #
# - Original location for bash to work - #
╭── # is_derayo@uServer-Ollama /Data/Backup :
╰─▷ $ ./OllamaBackup.sh



xdg-user-dirs-update;
sudo apt install dialog duf curl figlet git lolcat neovim pv webapp-manager -y;
sudo apt install dialog duf curl figlet git htop inxi lolcat net-tools neovim pv webapp-manager -y;

bash <(curl -s https://www.education.isdevelopment.us/OpenClaw-AI/OllamaBackup.sh)

# -  - #
# - Timezone setting - #
sudo timedatectl set-timezone America/New_York;
timedatectl;



rm -rf ~/.bashrc;
vim ~/.bashrc;

rm -rf ~/.zshrc;
vim ~/.zshrc;


ssh-keygen -R 192.168.1.1

# - On client - #
cd ~/.ssh;
ssh-keygen -t rsa;

cat ~/.ssh/id_rsa.pub;

# - On server - #
vim ~/.ssh/authorized_keys;



alias | grep uO;

# -  - #
# - Show existing ssh tunnels - #
sudo lsof -i -n | egrep '\<ssh\>'

# -  - #
# - To test - #
# - Create ssh tunnels in your Desktop - #
alias UpSshTunnel='ssh -L 18789:localhost:18789 -fN root@192.168.1.222;';
alias DownSshTunnel='pkill -f "ssh -L 18789:localhost:18789 -fN root@192.168.1.222;"';

ssh -SO exit is_derayo@192.168.1.222;
ssh -S <path-to-socket> -O exit is_derayo@192.168.1.222;

comment



# -  - #
# - VariablesDefinition_ - #
function VariablesDefinition_(){
  # -  - #
  # - Prepare Backup origen & destination folder - #
  oD_="/home/is_derayo/.ollama/models/";
  dD_="/Data/Backup/OllamaModels/";
  tF_="OllamaModelsBackup_"$(date +%Y-%m-%d_%H-%M-%S).tar.gz;
  dF_=$dD_$tF_
}



# -  - #
# - Header_ - #
function Header_(){
  clear;
  echo "";
  #figlet -f small "Arch Linux" | lolcat;
  figlet "Ollama" | lolcat;
  figlet "Backup Restore" | lolcat;
}



# -  - #
# - BackupRestore_Menu_ - #
function BackupRestore_Menu_(){
  Header_;
  echo -e "by Djalmar Enrique Rayo (2025) - GNU General Public License (GPL)";
  echo -e "\n   1. Backup"
  echo -e "   2. Restore"
  echo -e "   q. Quit"

  echo -e "\n";

  while true; do
    read -p "Enter option (1 2 Qq): " BRo_
    case $BRo_ in
        1 )
            echo -e "\n\n\nInstallation starting...\n\n"
            StopOllama_;
            BackupOllama_;
            RestartOllama_;
            exit          
            break;;
        2 )
            echo -e "\n\n\nInstallation starting...\n\n"
            StopOllama_;
            RestoreOllama_;
            RestartOllama_;
            exit          
            break;;
        [Qq]* )
          exit;
          break;;
        * ) echo "Please valid options...";;
    esac
  done
}



# -  - #
# - StopOllama_ - #
function StopOllama_(){
  docker compose -f /home/is_derayo/ollama-docker/docker-compose.yml stop;
  echo -e "\n\nOllama was stopped successfully ...\n\n\n";
}



# -  - #
# - RestartOllama_ - #
function RestartOllama_(){
  docker compose -f /home/is_derayo/ollama-docker/docker-compose.yml start;
  echo -e "\n\nOllama started successfully ...\n\n\n";
}



# -  - #
# - BackupOllama_ - #
function BackupOllama_(){
  local sM_='Ollama models';
  echo -e "\n\n\nCreating ollama models backup...\n\n";
  # - Create destination folder - #
  sudo mkdir -p $dD_;

  # - Create Backup - #
  SIZE=$(\du -sb "$oD_" | awk '{print $1}')
  (tar cf - "$oD_" | pv -n -s "$SIZE" -i 0.3 > "$dF_") 2>&1 \
                   | dialog --gauge "Creating $sM_ backup... \
                   \nOrigen: $oD_\nDestin: $dD_\n   Tar: $tF_" 10 70 0;
  DryRunRestore_;
  rSyncToProxmoxMini_;

  echo -e "\n\n$sM_ backup was created successfully...\n\n\n";
}



# -  - #
# - rSyncToProxmoxMini_ - #
function rSyncToProxmoxMini_(){
<<'comment'
  # -  - #
  #  --dry-run  #
  dD_="/Data/Backup/OllamaModels/";
comment
  rsync -avvhP --mkpath $dF_ \
          is_derayo@192.168.1.16:$dD_$tF_;
  echo -e "\n\n"$dF_;
  echo -e "\nCheck this file content & verify they are the right files,";
  sleep 10;
}



# -  - #
# - DryRunRestore_ - #
function DryRunRestore_(){
  # -  - #
  # - Dry-run to test content - #
  #dF_=OllamaModelsBackup_2026-04-21_12-18-19.tar.gz
  tar -tvf $dF_;
  echo -e "\n\n"$dF_;
  echo -e "\nCheck this file content & verify they are the right files,";
  echo -e "10 seconds pause...";
  sleep 10;
}



# -  - #
# - RestoreOllama_ - #
function RestoreOllama_(){
  local sM_='Ollama models';
  clear;
  echo -e "\n\n\nRestoring ollama models...\n\n";
  #DryRunRestore_;
  # - Create original folder - #
  sudo mkdir -p $oD_;

  # - Restore Backup - #

<<'comment'
  BACKUP_DIR="/Data/Backup/OllamaModels/"
         oD_="/home/is_derayo/.ollama/models/";
  RESTORE_TO="/home/is_derayo/.ollama/models/"    # Change to your restore destination
comment

  BACKUP_DIR=$dD_;
  RESTORE_TO=$oD_;

  # Colors for terminal output
  RED='\033[0;31m'
  GREEN='\033[0;32m'
  YELLOW='\033[1;33m'
  NC='\033[0m'

  # Get all backup files into array (oldest first)
  cd "$BACKUP_DIR" || return 1
  # FIXED: ls -1tr shows oldest first (matches 'la' order)
  mapfile -t BACKUPS < <(ls -1tr *.tar.gz 2>/dev/null)

  if [ ${#BACKUPS[@]} -eq 0 ]; then
    echo -e "${RED}No backup files found in $BACKUP_DIR${NC}"
    return 1
  fi

  # Show numbered list
  echo -e "${YELLOW}Available backups:${NC}"
  echo "-------------------"
  for i in "${!BACKUPS[@]}"; do
    SIZE=$(stat -c%s "${BACKUPS[$i]}" | numfmt --to=iec)
    DATE=$(stat -c%y "${BACKUPS[$i]}" | cut -d'.' -f1)
    printf "%2d) %-50s %8s  [%s]\n" $((i+1)) "${BACKUPS[$i]}" "$SIZE" "$DATE"
  done
  echo "-------------------"

  # Get user choice
  read -p "Select backup to restore (1-${#BACKUPS[@]}, or 'q' to quit): " CHOICE

  if [[ "$CHOICE" == "q" ]] || [[ "$CHOICE" == "Q" ]]; then
    echo "Cancelled."
    return 0
  fi

  # Validate choice
  if ! [[ "$CHOICE" =~ ^[0-9]+$ ]] || [ "$CHOICE" -lt 1 ] || [ "$CHOICE" -gt ${#BACKUPS[@]} ]; then
    echo -e "${RED}Invalid selection${NC}"
    return 1
  fi

  SELECTED="${BACKUPS[$((CHOICE-1))]}"
  SIZE=$(stat -c%s "$SELECTED")

  echo -e "\n${GREEN}Selected: $SELECTED${NC}"
  echo -e "${GREEN}Size: $(numfmt --to=iec $SIZE)${NC}"
  echo -e "${GREEN}Restoring to: $RESTORE_TO${NC}"
  echo ""

  # Confirm
  read -p "Proceed with restore? (y/N): " CONFIRM
  [[ "$CONFIRM" != "y" && "$CONFIRM" != "Y" ]] && return 0
  # Create restore directory if needed
  mkdir -p "$RESTORE_TO"

  # Restore with progress
  echo -e "${YELLOW}Restoring (this may take a while)...${NC}"

  if file "$SELECTED" | grep -q "gzip"; then
    # It's gzipped
    EXTRACT_CMD="tar xzf - --skip-old-files -C \"/\""
  else
    # It's plain tar
    EXTRACT_CMD="tar xf - --skip-old-files -C \"/\""
  fi

  ( pv -n -s "$SIZE" -i 0.5 "$SELECTED" | eval "$EXTRACT_CMD") 2>&1 \
          | dialog --gauge "Restoring $sM_ backup...\
          \nOrigen: $dD_\nDestin: $oD_\n   Tar: $SELECTED" 10 70 0

  if [ $? -eq 0 ]; then
    echo -e "\n${GREEN}✓ Restore completed successfully!${NC}"
    echo -e "${GREEN}Files restored to: $RESTORE_TO${NC}"
  else
    echo -e "\n${RED}✗ Restore failed${NC}"
    return 1
  fi

  echo -e "\n\nOllama models backup was restored successfully...\n\n";
}



VariablesDefinition_;
BackupRestore_Menu_;



<<'comment'
Summary Checklist
comment

# - eof - #