#!/bin/bash
#
# Crea un fichero /etc/pkgsync/musthave con la lista de paquetes instalados de forma
# intencionada en el sistema.
# Normalmente lo utilizamos para mantener el mismo software instalado en una serie de máquinas
# mediante pkgsync, aunque también podríamos usarlo para clonar los paquetes instalados en otra
# máquina con dpkg --set-selections.
#
# 2013-2024 Esteban M. Navas Martín <algodelinux@gmail.com>.
#

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

if (( $EUID != 0 )); then
   echo -e "${RED}Please run with SUDO or root user account${NC}"
   exit 1
fi

test -d /etc/pkgsync || mkdir /etc/pkgsync
test -f /etc/pkgsync/mayhave || touch /etc/pkgsync/mayhave
test -f /etc/pkgsync/maynothave || touch /etc/pkgsync/maynothave

codename=`lsb_release --codename | cut -f2`

case $codename in
"squeeze")
  test -s /etc/pkgsync/musthave && mv /etc/pkgsync/musthave /etc/pkgsync/musthave.$(date +"%Y%m%d") && echo -e "${GREEN}Realizando backup de /etc/pkgsync/musthave en /etc/pkgsync/musthave.$(date +'%Y%m%d')${NC}"

  echo -e "${GREEN}Generando lista de paquetes instalados en /etc/pkgsync/musthave...${NC}"
  aptitude show "?installed ?not(?priority(required)) ?not(?essential) ?not(?automatic)" | grep -e ^Package -e ^Paquete | cut -f 2 -d " " | sort > /etc/pkgsync/musthave
  ;;
"wheezy"|"jessie"|"bullseye"|"bookworm")
  test -s /etc/pkgsync/musthave && mv /etc/pkgsync/musthave /etc/pkgsync/musthave.$(date +"%Y%m%d") && echo -e "${GREEN}Realizando backup de /etc/pkgsync/musthave en /etc/pkgsync/musthave.$(date +'%Y%m%d')${NC}"

  echo -e "${GREEN}Generando lista de paquetes instalados en /etc/pkgsync/musthave...${NC}"
  aptitude show "?installed ?not(?priority(required)) ?not(?essential) ?not(?automatic)" | grep -e ^Package -e ^Paquete | cut -f 2 -d " " | sort > /etc/pkgsync/musthave
  echo -e "${GREEN}Obteniendo lista de paquetes multiarch...${NC}"
  aptitude show "?installed ?multiarch(same)" | grep -e ^Package -e ^Paquete | cut -f 2 -d " " > /tmp/same
  sort -u -o /tmp/same /tmp/same

  echo -e "${GREEN}Procesando lista de paquetes multiarch...${NC}"
  for paquete in `cat /tmp/same`; do
      sed -i 's|$paquete||' /etc/pkgsync/musthave
      dpkg -l|grep "$paquete:i386" 1>/dev/null && echo "$paquete:i386" >> /etc/pkgsync/musthave
      dpkg -l|grep "$paquete:amd64" 1>/dev/null && echo "$paquete:amd64" >> /etc/pkgsync/musthave
  done
  sort -u -o /etc/pkgsync/musthave /etc/pkgsync/musthave
  ;;
"trusty"|"bionic"|"jammy")
  test -s /etc/pkgsync/musthave && mv /etc/pkgsync/musthave /etc/pkgsync/musthave.$(date +"%Y%m%d") && echo -e "${GREEN}Realizando backup de /etc/pkgsync/musthave en /etc/pkgsync/musthave.$(date +'%Y%m%d')${NC}"

  echo -e "${GREEN}Generando lista de paquetes instalados en /etc/pkgsync/musthave...${NC}"
  aptitude search '~i !~M' -F '%p' --disable-columns | sort -u > /etc/pkgsync/musthave
  sort -u -o /etc/pkgsync/musthave /etc/pkgsync/musthave
  ;;
esac

echo -e "${GREEN}Proceso concluido.${NC}"