#!/bin/bash
#-device virtio-serial -chardev spicevmc,id=vdagent,debug=0,name=vdagent \
#-device virtserialport,chardev=vdagent,name=com.redhat.spice.0 \
#-spice port=7100,disable-ticketing \

export QEMU_AUDIO_DRV=alsa
export SPICE_DEBUG_ALLOW_MC=1

usage()
{
cat << EOF
usage: $0 options

#ToDo Write some useful description

OPTIONS:
  -h      Show this message
  -a      ISO architecture, should be 'i386' or 'amd64'
  -f      'cinnamon','gnome','lxde','lxqt','kde','mate','nox','xfce','xorg'
  -k      Keyboard
  -r      release: '', 'current','next','xperimental'
  -s      smp - 1..8 (default: 2)
  -u      UEFI-Boot
  -v      VGA-Option ('qxl', 'std', 'cirrus' Standard: qxl)
  -p      Server port for spice
EOF
}


if [ -f ./isobuilder.conf ]; then
    . ./isobuilder.conf
elif [ -f /etc/isobuilder/isobuilder.conf ]; then
    . /etc/isobuilder/isobuilder.conf
else
    echo "Please create a valid configuration in /etc/isobuilder or current dir!"
    exit 1
fi

BIOSDISPLAY='BIOS'

while getopts “a:f:i:k:p:r:s:t:v:hu” OPTION; do
    case ${OPTION} in
        a)
            IsoArch=${OPTARG}
            ;;
        f)
            IsoFlavour=${OPTARG}
            ;;
        i)
            IsoFile=$(realpath ${OPTARG})
            ;;
        k)
            Keyoard=${OPTARG}
            ;;
        p)
            OptSpicePort=${OPTARG}
            ;;
        r)
            ReleaseCode=${OPTARG}
            ;;
        s)
            SMP=${OPTARG}
            ;;
        h)
            usage
            exit
            ;;
        u)
            UEFI=true
            UEFIBIOS='-bios /usr/share/qemu/OVMF.fd'
            BIOSDISPLAY='UEFI'
            ;;
        v)
           VGA=${OPTARG}
           ;;
    esac
done

case ${ReleaseCode} in
    current)
        IsoRelease=${CurrentReleaseName}
        ;;
    next)
        IsoRelease=${NextReleaseName}
        ;;
    xperimental)
        IsoRelease=${XperimentalReleaseName}
        ;;
    *)
        echo "ReleaseCode nicht bekannt ${ReleaseCode}"
        ;;
esac

if [ -z ${IsoFlavour} ] || [ -z ${IsoArch} ]; then
     usage
     exit 1
fi

if [ "x${IsoFile}" == "x" ]; then
   SearchIso="${IsoPath}/${IsoFlavour}/${IsoArch}/*${IsoRelease}*iso"
   IsoFile=$(ls --sort=time ${SearchIso} | head -n1)
   StrippedIsoFile=$(echo "$IsoFile" | sed "s#${IsoPath}##")
fi

if [ "x${IsoFile}" == "x" ]; then
    echo ""
    echo "================================================"
    echo "Isofile with Searchpattern ${SearchIso} not found!"
    echo "eventually you would like one of these images:  "
    echo ""
    ls ${IsoPath}/${IsoFlavour}/${IsoArch}/*iso
    echo ""
    echo "Quitting now"
    exit 0
fi

IsoName=$(basename ${IsoFile%.*})
IsoVersion=$(echo ${IsoName}  | awk -F '-' '{ print  $2 }')  # 13.1.1
IsoRelease=$(echo ${IsoName}  | awk -F '-' '{ print  $3 }')  # paintitblack
IsoFlavour=$(echo ${IsoName}  | awk -F '-' '{ print  $4 }')  # nox
IsoDateTime=$(echo ${IsoName} | awk -F '-' '{ print  $(NF) }' | sed "s/\([0-9]\{4\}\)\([0-9]\{2\}\)\([0-9]\{2\}\)\([0-9]\{2\}\)/\1-\2-\3_\4-/1" ) # datetime

case ${IsoFlavour} in
    cinnamon)
        SpicePort=7210
        ;;
    gnome)
        SpicePort=7220
        ;;
    kde)
        SpicePort=7230
        ;;
    lxde)
        SpicePort=7240
        ;;
    lxqt)
        SpicePort=7250
        ;;
    mate)
        SpicePort=7260
        ;;
    nox)
        SpicePort=7270
        ;;
    xfce)
        SpicePort=7280
        ;;
    xorg)
        SpicePort=7290
        ;;
    *)
        SpicePort=6666;
        ;;
esac

case ${IsoArch} in
    amd64)
        SpicePort=${SpicePort}
        ;;
    i386)
        SpicePort=$(expr ${SpicePort} + 1000)
        ;;
esac

case ${ReleaseCode} in
    current)
        SpicePort=${SpicePort}
        ;;
    next)
        SpicePort=$(expr ${SpicePort} + 100)
        ;;
    xperimental)
        SpicePort=$(expr ${SpicePort} + 200)
        ;;
esac


## OptSpicePort ToDo ##
## spice-vdagebt ToDo ##

echo ""
echo ""
echo "=============================="
echo "=     KVM   Spice   ${BIOSDISPLAY}     ="
echo "=============================="
echo "Iso-Version:  ${IsoVersion}"
echo "Iso-Flavour:  ${IsoFlavour}"
echo "Architecture: ${IsoArch}"
echo "Release:      ${IsoRelease}"
echo "Iso-File:     ${IsoFile}"
echo "SMP:          ${SMP}"
echo "Date/Time:    ${IsoDateTime}"
echo "Spice-Port:   ${SpicePort}"
echo ""
echo "Download:     ${IsoHost}${StrippedIsoFile}"
echo ""
echo ""

qemu_args=(
    -name siduction-${IsoFlavour}
    #-machine pc,accel=kvm
    -machine q35,accel=kvm
    ${UEFIBIOS}
    -m 4096
    -balloon virtio
    -smp ${SMP}
    -usbdevice tablet

    -vga "${VGA}"
    -spice port="${SpicePort}",disable-ticketing

    -netdev user,id=nat0
    -device virtio-net,netdev=nat0 #,mac=52:54:01:00:00:07

    -device virtio-scsi-pci,id=hba0
    -drive if=none,id=sda,media=disk,cache=unsafe,file=${QcowPath}/${IsoFlavour}-${IsoArch}.qcow2
    -device scsi-hd,drive=sda

    -drive if=none,id=sr0,media=cdrom,file="${IsoFile}"
    -device scsi-cd,drive=sr0
    -boot order=dc

    -device virtio-serial-pci
    -device virtserialport,chardev=spicechannel0,name=com.redhat.spice.0
    -chardev spicevmc,id=spicechannel0,name=vdagent
)

qemu-system-x86_64 "${qemu_args[@]}" # append "$@" here to allow for additional options

