#!/bin/bash
if [ ! -f $HOME/.guix/qemu/guix-user.qcow2 ]
then
    /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
    tar -xvzf $HOME/.guix/qemu/guix.qcow2.tar.gz -C $HOME/.guix/qemu/
fi

if [ ! -f $HOME/.guix/home/.bashrc ]
then
touch $HOME/.guix/home/.bashrc
echo 'DISPLAY=' > $HOME/.guix/home/.bashrc
echo 'CC=gcc' >> $HOME/.guix/home/.bashrc
#echo 'if [ ! -w "~/.bashrc" ]' >> $HOME/.guix/home/.bashrc
#echo 'then' >> $HOME/.guix/home/.bashrc
#echo  '    sudo chown -R admin /mnt/macos' >> $HOME/.guix/home/.bashrc
#echo  'fi' >> $HOME/.guix/home/.bashrc
fi

if [ -f /opt/X11/bin/xquartz ]
then
    IP=$(/usr/sbin/ipconfig getifaddr en0)
    /opt/X11/bin/xhost + "$IP"
    sed -i'' -e "s/.*DISPLAY.*/export DISPLAY=$IP:0/g" $HOME/.guix/home/.bashrc 
fi

chmod 700 $HOME/.guix/ssh-cert/msg_rsa

echo "GUIX is now running"

/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 $HOME/.guix/qemu/QEMU_EFI.fd \
    -device virtio-net,netdev=vmnic \
    -netdev user,id=vmnic,hostfwd=tcp:127.0.0.1:9001-:22 \
    && exit

