#!/bin/bash

VM_PATH=/etc/pve/qemu-server
PVE_PATH=/etc/pve
LOCAL_VM_PATH=/etc/pve/local/qemu-server
SERIAL_PATH=/var/run/qemu-server

if [[ ! -d /etc/pve ]]; then
    echo "Not a proxmox server !"
    exit 1
fi

if [[ -z "$1" ]]; then
    echo "Please give vmid or pve name"
    exit 5
fi

if [[ "`whoami`" != "root" ]]; then
    echo "You must probably be root"
    exit 42
fi

if [[ $1 != *[!0-9]* ]]; then
    vmid=$1
else
    echo "Looking for vmid of $1 ..."
    for host in `ls $PVE_PATH/nodes`; do
        p=$PVE_PATH/nodes/$host/qemu-server
        for f in `ls $p`; do
            grep "name: *$1" $p/$f -q && {
                vmid=`echo $f | grep -o "[0-9]*"`
                node=$host
                echo "Found vmid $vmid"
                break
            }
        done
    done
    if [[ -z "$node" ]]; then
        echo "vmid not found"
        exit 2
    elif [[ "$node" != "`hostname`" ]]; then
        echo "Wrong node (go to $node)"
        exit 3
    fi
fi
shift

device=$SERIAL_PATH/$vmid.serial

if [[ ! -S $device ]]; then
    echo "$device missing (vm misconfigured or shutdown ?)"
    exit 4
fi

minicom -R utf-8 -D unix#$device "$@"
