#!/bin/bash

workpath="$1"
containerid="$2"
crundir="$3"

bundle=$( cat "$crundir"/bundle )
pidfile=$( cat "$crundir"/pidfile )
configfile="$bundle"/config.json
mountpoint=$( cat "$crundir"/rootfs )
appname=$(cat "$configfile" | jq '.["Path"]')
cmdline=\"$(cat "$configfile" | jq  -c -r '.["process"]["args"] | join("\" \"")')\"
env=$(cat "$configfile" | jq  -c -r '.["process"]["env"] | join("\" \"")')
kernel="$workpath/kernel"
ramdisk="$workpath/initrd"
vm_uuid_file="$crundir/xcp_vm_uuid"
vdi_uuid_file="$crundir/xcp_vdi_uuid"
container_pipe="$crundir/container_pipe"

for i in $env
do
    i=$(echo "$i" | tr -d \")
    if [[ $i = RUNX_KERNEL=* ]]
    then
        kernel=${i#RUNX_KERNEL=}
        kernel="$mountpoint"/"$kernel"
    fi
    if [[ $i = RUNX_RAMDISK=* ]]
    then
        ramdisk=${i#RUNX_RAMDISK=}
        ramdisk="$mountpoint"/"$ramdisk"
    fi
done

sr_uuid=""
template_uuid=""
guest_tools=""
for i in $( cat /etc/runx.conf )
do
    i=$(echo $i | tr -d \")
    if [[ $i = SR_UUID=* ]]
    then
        sr_uuid=${i#SR_UUID=}
    fi
    if [[ $i = TEMPLATE_UUID=* ]]
    then
        template_uuid=${i#TEMPLATE_UUID=}
    fi
    if [[ $i = GUEST_TOOLS=* ]]
    then
        guest_tools=${i#GUEST_TOOLS=}
        if [ -f "$guest_tools" ]; then
            guest_tools=$(cat "$guest_tools")
        fi
    fi
done

sr_uuid=$( xe sr-list uuid="$sr_uuid" --minimal )
if ! test "$sr_uuid"
then
    echo "no sr found"
    exit 1
fi

template_uuid=$( xe template-list uuid="$template_uuid" --minimal )
if ! test "$template_uuid"
then
    echo "no template found"
    exit 1
fi

# netconf is file,type[,ip]
netconf=$(cat "$configfile" | jq  -c -r  '.["process"]["env"][] | select(contains("NETCONF"))')
netconf=$(echo "$netconf" | awk -F "=" '{print $2}')
if test "$netconf"
then
    netfile=$(echo "$netconf" | awk -F "," '{print $1}')
    netname=$(echo "$netconf" | awk -F "," '{print $2}')
    netaddr=$(echo "$netconf" | awk -F "," '{print $3}')
    nettype=$(cat "$netfile" | jq -c -r "select(.[\"name\"] == \"$netname\") | .[\"type\"]")

    if test "$nettype" = "bridge"
    then
        pvcalls=0
        bridge=$(cat "$netfile" | jq -c -r "select(.[\"name\"] == \"$netname\") | .[\"bridge\"]")
        gw=$(cat "$netfile" | jq -c -r "select(.[\"name\"] == \"$netname\") | .[\"ipam\"][\"gateway\"]")
        route=$(cat "$netfile" | jq -c -r "select(.[\"name\"] == \"$netname\") | .[\"ipam\"][\"subnet\"]")
        dns=$(cat "$netfile" | jq -c -r "select(.[\"name\"] == \"$netname\") | .[\"dns\"][\"nameservers\"]")
    else
        #shouldn't get here, but if we do assume pvcalls
        pvcalls=1
    fi
else
    pvcalls=1
fi

vm_name_label="container:$containerid"

vm_uuid=$(xe vm-install new-name-label="$vm_name_label" template="$template_uuid" --minimal)
vdi_uuid=$(xe vdi-create sr-uuid="$sr_uuid" name-label="$mountpoint" virtual-size=1KiB)
vbd_uuid=$(xe vbd-create vm-uuid="$vm_uuid" device=1 vdi-uuid="$vdi_uuid" bootable=false mode=RW type=Disk)

pv_args=$(xe vm-param-get param-name=PV-args uuid=$vm_uuid)

if test "$netaddr"
then
    pv_args="$pv_args ip=$netaddr gw=$gw route=$route dns=$dns bridge=$bridge"
else
    pv_args="$pv_args ip=dhcp bridge=$bridge"
fi

xe vm-param-set uuid="$vm_uuid" PV-args="$pv_args root=9p rdinit=/bin/init pvcalls=$pvcalls"
xe vm-param-set uuid="$vm_uuid" PV-kernel="/boot/guest/runx/kernel"
xe vm-param-set uuid="$vm_uuid" PV-ramdisk="/boot/guest/runx/initrd"

runx_dir="$mountpoint/run/runx"

# Install tools.
if [ "$guest_tools" ]; then
    rpm -i --prefix="$mountpoint" "$guest_tools/*.rpm"
fi

# Set command line.
mkdir -p "$runx_dir"
echo "$cmdline" > "$runx_dir"/cmdline

# Share ENV variables.
env_variables=$(cat "$configfile" | jq  -c -r '.["process"]["env"] | join("\n")')
echo "$env_variables" > "$runx_dir/env"

# Specify Working dir.
working_dir=$(cat "$configfile" | jq  -c -r '.["process"]["cwd"]')
echo -n "$working_dir" > "$runx_dir/working_dir"

# Copy or bind config files.
config_files=$(cat "$configfile" | jq -c -r '.["mounts"] | map(select(.destination == ("/etc/resolv.conf","/etc/hostname","/etc/hosts","/run/secrets")) | "\(.source);\(.destination)") | .[]')
for config in $config_files; do
    config_source=${config%;*}
    config_dest=$mountpoint/${config#*;}

    if [ -d "$config_source" ]; then
        mount -o nonempty --bind "$config_source" "$config_dest"
    elif [ -f "$config_source" ]; then
        # I don't know why but podman creates folders by default...
        rm -rf "$config_dest"
        cp "$config_source" "$config_dest"
    fi
done

echo -n "$vm_uuid" > "$vm_uuid_file"
echo -n "$vdi_uuid" > "$vdi_uuid_file"

# Idea: We start a small program called "container-wrapper" to wait for a SIGINT, SIGABORT or SIGKILL.
# This program can be destroyed by docker using "docker kill...", when this last one is killed, a second
# program called "container" executes "xe vm-destroy, vdi-destroy...".
# Otherwise with only one script we can't clean and shutdown properly the VM if a SIGKILL is received.
mkfifo "$container_pipe"
"$workpath/container-wrapper" &
wrapper_pid="$!"
"$workpath/container" "$workpath" "$vm_uuid" "$vdi_uuid" "$wrapper_pid" "$container_pipe" &

# Set the PID to make Docker happy.
echo -n "$wrapper_pid" > "$pidfile"
