#!/bin/bash

workpath=/usr/share/runX
rundir=/run/runX

guestconsole=""
cmd=""
root=""
bundle=""
pidfile=""
containerid=""
while (( "$#" ))
do
    if [[ $1 = "--root" ]]
    then
        root=$2
        shift
        shift
        continue
    fi
    if [[ $1 = "--bundle" ]]
    then
        bundle=$2
        shift
        shift
        continue
    fi
    if [[ $1 = "--pid-file" ]]
    then
        pidfile=$2
        shift
        shift
        continue
    fi
    if [[ $1 = "--console-socket" ]]
    then
        guestconsole="$2"
        shift
        shift
        continue
    fi
    if [[ $1 = "--no-pivot" ]]
    then
        shift
        continue
    fi
    if [[ $1 = "--"* ]]
    then
        shift
        shift
        continue
    fi
    if test -z "$cmd"
    then
        cmd=$1
        shift
        continue
    fi
    containerid=$1
    break
done

if ! test "$containerid"
then
    echo "no containerid given, exiting"
    exit 1
fi

crundir="$rundir"/"$containerid"

if test "$cmd" = "create"
then
    rm -rf "$crundir"
fi

if test ! -d "$crundir"
then
    mkdir -p "$crundir"
fi

if test \( "$bundle" \) -a \( ! -f "$crundir"/bundle \)
then
    echo -n "$bundle" > "$crundir"/bundle

    if  test -f "$bundle"/config.json
    then
        rootfs="$( jq -r -c  '.["root"]["path"]' "$bundle"/config.json )"
        if [[ "$rootfs" != /* ]]
        then
            rootfs="$bundle"/"$rootfs"
        fi
        echo -n "$rootfs" > "$crundir"/rootfs
    else
        echo "can't determine rootfs, erring out"
        exit 1
    fi
fi

if test \( "$pidfile" \) -a \( ! -f "$crundir"/pidfile \)
then
    echo -n "$pidfile" > "$crundir"/pidfile
fi

if test $cmd = "state"
then
    $workpath/state $containerid "$crundir"
elif test $cmd = "start"
then
    $workpath/start $containerid
elif test $cmd = "pause"
then
    $workpath/pause $containerid pause
elif test $cmd = "resume"
then
    $workpath/pause $containerid resume
elif test $cmd = "kill"
then
    $workpath/delete $containerid
    $workpath/mount $containerid "$crundir" unmount
elif test $cmd = "create"
then
    $workpath/mount $containerid "$crundir" mount
    $workpath/create $containerid "$crundir"

    if test "$guestconsole"
    then
        daemonize $workpath/serial_start \
          "$containerid" \
          "$crundir"/console_pty
        for n in 10 9 8 7 6 5 4 3 2 1; do
            if [ ! -L "$crundir"/console_pty ]; then
              sleep .1
            else
              break
            fi;
        done
        daemonize $workpath/sendfd \
          "$guestconsole" \
          "$crundir"/console_pty
    else
         echo "connect to container console with 'xl console $containerid'"
    fi
elif test $cmd = "delete"
then
    rm -rf "$crundir"
else
    :
fi
