#!/bin/bash

# set -x # For debugging
set -eo pipefail # No -u that would just bother me
trap cleanup EXIT # A little more robust cleanup

if [ "$(id -u)" != "0" ]; then
    echo "You should run this script as root"
    sleep 3
    # exit 1
fi

# Check the OS, it sets a env variable as a result
source ./os_probe.bash
source ./check.bash

# Some menu things

# colors
# red = 1
# green = 2
# yellow = 3
# blue = 4 

function cprint () { 
    color="$1"
    shift
    echo "$(tput setaf $color)$*$(tput sgr0)"

}

function mprint (){
    echo "    	$1  -  $2"
}

function incorrect_selection() {
  cprint 1 "Incorrect selection! Try again."
}

function press_enter() {
  echo ""
  cprint 3 "Press Enter to continue "
  read
  clear
}

function copy_config() {
  cprint 2 "Creating restorable package..."
  sleep 1
  tmpdir=$(mktemp -d)
  echo $tmpdir
  cp -r /etc/ $tmpdir
  if [ -f ./exclusions ]; then
    cp ./exclusions $tmpdir
  fi
 if [ "$osp" = "Debian" ]; then
  dpkg --get-selections > $tmpdir/installed_packages  
  cp ./restore.deb.bash $tmpdir/restore.bash
  #apt list --installed | grep ',local]' | awk -F/ '{print $1}' >> $tmpdir/exclusions
  apt list --installed | grep -q ',local]' && apt list --installed | grep ',local]' | awk -F/ '{print $1}' >> "$tmpdir/exclusions"

fi

if [ "$osp" = "Arch" ]; then
    pacman -Qqen > $tmpdir/installed_packages
    cp ./restore.arch.bash $tmpdir/restore.bash
fi

if [ "$osp" = "Openwrt" ]; then
    opkg list-installed > $tmpdir/installed_packages
    cp ./restore.wrt.bash $tmpdir/restore.bash
    cp ./bootstrap.wrt.ash $tmpdir
fi
  
  arcdir=$(mktemp -d)
  echo $arcdir
 
  echo $mkslf
  if [ "$osp" = "Openwrt" ]; then

  $mkslf --gzip $tmpdir $arcdir/restore.run "SFX archive for restoration" ./bootstrap.wrt.ash

  else
  
  $mkslf --gzip $tmpdir $arcdir/restore.run "SFX archive for restoration" ./restore.bash
  
  fi
  cp $arcdir/restore.run ./
  
  cprint 2 "Done!"

}

function menu_option_two() {
  cprint 2 "Installing makeself..."
  sleep 1
  wget https://github.com/megastep/makeself/releases/download/release-2.5.0/makeself-2.5.0.run
  chmod +x makeself-2.5.0.run
  ./makeself-2.5.0.run
  cd makeself-2.5.0
  cp *.sh /usr/bin
  cprint 2 "Done!"
}

function cleanup() {
  if [ $? -ne 0 ]; then 
  cprint 1 "Something exploded and program aborted"
  fi
  cprint 2 "Cleaning up..." 
  sleep 1   
  rm -rf $tmpdir
  rm -rf $arcdir

}

until [ "$selection" = "0" ]; do
clear
  echo ""
  cprint 3 "          Main Menu"
  mprint 1 "Create a self restorable package"
  mprint 2 "Install makeself(required) to create self restorable package"
  mprint 0 "Exit"
  echo ""
  echo -n "  Enter selection: "
  read selection
  echo ""
  case $selection in
    1 ) clear ; copy_config ; press_enter ;;
    2 ) clear ; menu_option_two ; press_enter ;;
    0 ) clear ; exit ;;
    * ) clear ; incorrect_selection ; press_enter ;;
  esac
done
