(define-module (msg machine)
  #:use-module (ice-9 match)
  #:use-module (ice-9 rdelim)
  #:use-module (ice-9 textual-ports)
  #:use-module (system foreign)
  #:use-module (msg helpers)
  #:export (machine))


(define* (machine #:optional (args (command-line)))
  ;;(define clean-args (cdr args))
  (match args
    (("-h")
     (help))
    (("init")
     (init))
    (("reinit")
     (clear-install)
     (init))
    (_
     (display "Please enter a valid command or -h for help.\n"))))

(define* (help)
  (display "\nHere are the available commands:\n\n")
  (display "start: Start the MSG envrionment.\n"))

(define* (clear-install)
  (display "This is a destructive command and will remove your entire guix instance. Proceed? (y/n)\n")
  (define response (read-line))
  (if (string=? response "y")
      (begin
	(system "rm -r ~/.guix"))
      (display "Please enter a valid response.")))

(define* (init)
  (define home-path (getenv "HOME"))
  (define arch (run-shell-command "uname -m"))

  
  (if (not (directory-exists? (format #f "~a/.guix" home-path)))
      (begin
	(system "mkdir -p $HOME/.guix/qemu $HOME/.guix/home $HOME/.guix/ssh-cert")
	;; Get msg image

	(cond ((string=? arch "arm64")
	       (system "/opt/homebrew/bin/wget https://objectstorage.us-phoenix-1.oraclecloud.com/n/axfgkze2xif1/b/guix-system/o/msg-system-aarch64guix-user.qcow2.tar.gz -O $HOME/.guix/qemu/guix.qcow2.tar.gz")
	       (system "tar -xvzf $HOME/.guix/qemu/guix.qcow2.tar.gz -C $HOME/.guix/qemu/")
	       (define pid (run-shell-command "/opt/homebrew/bin/qemu-system-aarch64 \
    -machine virt,highmem=on \
    -accel hvf \
    -cpu host \
    -smp 4 \
    -display none \
    -hda $HOME/.guix/qemu/guix-user.qcow2 \
    -m 4G \
    -virtfs local,path=$HOME/.guix/home,security_model=mapped,mount_tag=macos \
    -bios /opt/homebrew/opt/qemu/share/qemu/edk2-aarch64-code.fd \
    -device virtio-net,netdev=vmnic \
    -netdev user,id=vmnic,hostfwd=tcp:127.0.0.1:9001-:22 &"))
	      (display pid))
	      ((string=? arch "x86_64")
	       (system "/usr/local/bin/wget https://objectstorage.us-phoenix-1.oraclecloud.com/n/axfgkze2xif1/b/guix-system/o/msg-system-x86_64guix-user-x86.qcow2.tar.gz -O $HOME/.guix/qemu/guix.qcow2.tar.gz")
	       (system "tar -xvzf $HOME/.guix/qemu/guix.qcow2.tar.gz -C $HOME/.guix/qemu/")
	       (system "/usr/local/bin/qemu-system-x86_64 \
    -machine type=q35,accel=hvf \
    -smp 4 \
    -hda $HOME/.guix/qemu/guix-user.qcow2 \
    -m 4G \
    -display none \
    -cpu Nehalem \
    -virtfs local,path=$HOME/.guix,security_model=mapped,mount_tag=macos \
    -device virtio-net,netdev=vmnic \
    -netdev user,id=vmnic,hostfwd=tcp:127.0.0.1:9001-:22")
	       ))
	
	;; Get msg ssh-key
	(system "/opt/homebrew/bin/wget https://objectstorage.us-phoenix-1.oraclecloud.com/n/axfgkze2xif1/b/guix-system/o/msg_rsa -O $HOME/.guix/ssh-cert/msg_rsa")))

  (system "ssh -o StrictHostKeychecking=no -i $HOME/.guix/ssh-cert/msg_rsa root@127.0.0.1 -p 9001 'guix'"))