#!/bin/bash
# fanta <fanta@56k.es>
qArch="x86_64" # i386,x86_64
hda="disco.qcow2"
mem="8192M"
diskSize="100G"
nCores="4"
serial="telnet:127.0.0.1:5001,server,nowait"
monitor="tcp:127.0.0.1:6001,server,nowait"
drive1="file=$hda,if=ide,index=0,media=disk"
kvm="-accel kvm"
cpu="host,vmx=off"
machine="q35,vmport=off"
nCores="2"

esx0="vmxnet3,mac=00:2e:3c:92:26:00,netdev=esx-0"
esx1="vmxnet3,mac=00:2e:3c:92:26:01,netdev=esx-1"
esx2="e1000,mac=00:2e:3c:92:26:02,netdev=esx-2"
esx3="e1000,mac=00:2e:3c:92:26:03,netdev=esx-3"

nesx0="socket,id=esx-0,udp=127.0.0.1:10000,localaddr=127.0.0.1:20000"
nesx1="socket,id=esx-1,udp=127.0.0.1:10001,localaddr=127.0.0.1:20001"
nesx2="socket,id=esx-2,udp=127.0.0.1:10002,localaddr=127.0.0.1:20002"
nesx3="socket,id=esx-3,udp=127.0.0.1:10003,localaddr=127.0.0.1:20003"


pwd="$(pwd)";path=${BASH_SOURCE[0]}
dir="$(echo "$pwd/$path"| rev | cut -d "/" -f2-100|rev)"
cd $dir
iso="$(ls -1 *.iso | head -1)"
opt="$1"

function who { if [ "$(whoami)" = "root" ]; then exit; fi }

function createQcow2 {
  qemu-img create -f qcow2 "$hda" $diskSize
}

function checkQcow2 { if [ ! -f "$dir/$hda" ]; then createQcow2; fi }

function bootCD {
  qemu-system-$qArch $kvm -m $mem -serial $serial -monitor $monitor -machine $machine -cpu $cpu -smp cpus=$nCores -boot d -cdrom $iso -drive $drive1 -net none -device $esx0 -device $esx1 -device $esx2 -device $esx3 -netdev $nesx0 -netdev $nesx1 -netdev $nesx2 -netdev $nesx3
}

function bootHD {
  qemu-system-$qArch -enable-kvm -m $mem -cpu host -smp cpus=$nCores -machine type=pc,accel=kvm -net nic,model=e1000 -hda $hda -net user
}

function showHelp {
  echo -e "start.sh - fanta <fanta@56k.es>\n"
  echo "--help Show this help"
  echo "--hd Boot from HD"
  echo -e "--cdrom To install system booting from iso (cdrom)\n"
}

function checkOpt {
  if [ -z "$opt" ]; then showHelp; fi
  if [ "$opt" = "--help" ]; then showHelp; fi
  if [ "$opt" = "--hd" ]; then bootHD; fi
  if [ "$opt" = "--cdrom" ]; then bootCD; fi
}

function main() {
  who
  checkQcow2
  checkOpt
}

main
