// Silly wrapper to use while waiting for libvirt to support spice directly.
// Replaces vga args with spice args and looks up the spice port number to
// use by finding the -name <name> argument and looking for the
// /zooty/images/<name>.spice file. If there is no such file, the arguments
// are not modified and the virtual machine does not run under spice.
//

#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>

#define IMAGEDIR "/zooty/images/"

int
main(int argc, char ** argv) {
   int i;
   int d = 0;
   const char * name = NULL;
   char * spicearg = NULL;

   // Go through the arguments first and find the -name arg

   for (i = 0; i < argc; ++i) {
      if (strcmp(argv[i], "-name") == 0) {
         name = argv[i+1];
         break;
      }
   }
   if (name != 0) {
      char * spicename = (char *)malloc(strlen(IMAGEDIR) + strlen(name) + 50);
      FILE * sf;
      strcpy(spicename, IMAGEDIR);
      strcat(spicename, name);
      strcat(spicename, ".spice");
      sf = fopen(spicename, "r");
      if (sf != NULL) {
         char buf[500];
         if (fgets(buf, sizeof(buf), sf) != NULL) {
            int bl = strlen(buf);
            while ((bl > 0) && isspace(buf[bl-1])) {
               --bl;
            }
            if (bl > 0) {
               buf[bl] = '\0';
               spicearg = (char *)malloc(bl + 10);
               strcpy(spicearg, buf);
            }
         }
         fclose(sf);
      }
   }

   if (spicearg != NULL) {
      char ** newargv = (char **)malloc(sizeof(char *)*(argc + 20));
      putenv("QEMU_AUDIO_DRV=spice");
      for (i = 0; i < argc; ++i) {
         if (i == 0) {
            newargv[d++] = "/usr/bin/qemu-kvm";
         } else if (strcmp(argv[i], "-vga") == 0) {
            newargv[d++] = "-global";
            newargv[d++] = "qxl.revision=2";
            newargv[d++] = argv[i];
            newargv[d++] = "qxl";
            ++i;
         } else if (strcmp(argv[i], "-vnc") == 0) {
            newargv[d++] = "-spice";
            newargv[d++] = spicearg; // "port=5930,disable-ticketing";
            newargv[d++] = "-device";
            newargv[d++] = "virtio-serial-pci,id=virtio-serial0,max_ports=16,bus=pci.0,addr=0x8";
            newargv[d++] = "-device";
            newargv[d++] = "spicevmc,nr=1,bus=virtio-serial0.0";
            ++i;
         } else {
            newargv[d++] = argv[i];
         }
      }
      newargv[d++] = NULL;
      execv(newargv[0], newargv);
   } else {
      argv[0] = "/usr/bin/qemu-kvm";
      execv(argv[0], argv);
   }
   exit(2);
}
