#!/bin/bash

# CREATE NETWORK DEVICES AS BRIDGE, NEVER AS VEPA, 'CUZ THIS CONFLICTS WITH MACVLAN DOCKER!

##############
# Parameters #
##############

pfsense_iso="pfsense2.8"

destpath="/var/lib/libvirt/images"

mkdir -p "$destpath"
chmod 777 -R "$destpath"

serverip="172.20.0.22"
lanhost="http://$serverip"
wanhost="http://z.net-freaks.com:3434"

usern4me="admin"
passw0rd="isorulez"

# Check where get the .img file
if ping -c 1 "$serverip" >/dev/null; then
    webadress="$lanhost"
else
    webadress="$wanhost"
fi

#############
# Functions #
#############

function check {
  [ "$EUID" -ne 0 ] && {
    echo "Execute esse script como Root!"
    exit 1
    }
}

function start {
  if [ -f "$destpath/$pfsense_iso" ]; then
    setinter
    echo "." >/dev/null
  else
    calling "$pfsense_iso"
    setperma
    setinter
  fi
}

function calling {
  clear
  wget --user "$usern4me" --password "$passw0rd" "$webadress/$1" -O "$destpath/$1"
}

function setperma {
  chmod 777 -R "$destpath"
}

function setinter {
  # Get main LAN (usually motherboard)
  mylan=$(ip route get 1.1.1.1 2>/dev/null | grep -oP 'dev \K\S+')

  # Create an Array but eliminating docker, veth, lo, tun, virbr, macv and myself (mylan) from that!
  myarray=()
  for iface in /sys/class/net/*; do
    iface=$(basename "$iface")
    case "$iface" in
      docker*|veth*|lo|virbr*|macv*|tun*|"$mylan")
        continue
        ;;
      *)
        myarray+=("$iface")
        ;;
    esac
  done

  # Set up initial values for dialog
  VALUE1="${myarray[0]}"
  VALUE2="${myarray[1]}"
  VALUE3="${myarray[2]}"
  VALUE4="${myarray[3]}"

  for i in {0..3}; do
    idx=$((i+1))
    var="VALUE$idx"
    if [[ -z "${myarray[$i]}" ]]; then
      printf -v "$var" "0"
    fi
  done

  VALUE0=$(dialog --help-button --help-label "Dica" --ok-label "Criar" --title "Definir Interfaces" --form "O que estiver zero nao sera utilizado!" 13 40 0 \
"IP LAN 0:" 1 1 "$VALUE1" 1 11 30 0 \
"IP LAN 1:" 2 1 "$VALUE2" 2 11 30 0 \
"IP LAN 2:" 3 1 "$VALUE3" 3 11 30 0 \
"IP LAN 3:" 4 1 "$VALUE4" 4 11 30 0 \
3>&1 1>&2 2>&3 3>&- > /dev/tty)

  case $? in
    0) echo "." > /dev/null ;;
    1) return ;;
    2) dialognet ; setinter ;;
  esac

  var1=$(echo "$VALUE0" | sed -n 1p)
  var2=$(echo "$VALUE0" | sed -n 2p)
  var3=$(echo "$VALUE0" | sed -n 3p)
  var4=$(echo "$VALUE0" | sed -n 4p)

  interfaces=()
  for v in "$var1" "$var2" "$var3" "$var4"; do
    [[ "$v" != "0" ]] && interfaces+=("$v")
  done

  createvm_dynamic "${interfaces[@]}"
}

function createvm_dynamic {
  local name="pfSense"
  local networks=("$@")
  local net_args=()
  local mac_prefix="52:54:00:55:ea"
  
  for i in "${!networks[@]}"; do
    local idx
    idx=$(printf "%02x" $((i+1)))
    net_args+=("--network" "type=direct,source=${networks[$i]},source_mode=bridge,mac=${mac_prefix}:${idx}")
  done

  virt-install --import \
    --name "$name" \
    --boot hd,cdrom,menu=on \
    --memory 2048 \
    --vcpus 2 \
    --cpu host \
    "${net_args[@]}" \
    --disk "$destpath/$pfsense_iso" \
    --os-variant=freebsd14.2 \
    --graphics vnc \
    --import \
    --autostart 1>/dev/null 2>/dev/null &

  dialog --title "Informação" --msgbox "Se a maquina virtual nao existia, ela sera criada e inicializada!" 6 40
  dialog --title "Informação" --msgbox "Verifique o status da maquina virtual pelo Virt-Manager, digitando o comando startx!" 6 60

  exit
}

function dialognet {
  dialog --title "Informação" --msgbox "Checar a existencia de altnames nas informacoes a seguir!" 7 40
  dialog --title "Informação" --msgbox "$(ip a)" 25 70
}

#########
# Start #
#########

check
start

exit 0
