#!/bin/bash

ME=${0##*/}

WORK_DIR=/run/$ME
FIFO=$WORK_DIR/fifo

CLI_PROG="live-usb-maker"
PROG_FILE="/var/log/$CLI_PROG.progress"
LOCK_FILE="/run/lock/$CLI_PROG"
LIB_FILE=/usr/local/lib/cli-shell-utils/cli-shell-utils.bash

main() {

    source $LIB_FILE || error "Could not source $LIB_FILE"

    trap clean_up EXIT
    gui_flock $LOCK_FILE || error  "already locked"
    mkdir -p $WORK_DIR

    mkfifo $FIFO
    exec 10<> $FIFO
    yad --text-info --width=880 --height=350 --tail --center  <&10 &
    local yad_pid=$!

    truncate -s0 $PROG_FILE
    tail -f --pid=$yad_pid $PROG_FILE >&10 &
    local tail_pid=$!
   
    sleep 1
    $CLI_PROG gui --force=flock "$@"
    echo -n "Press <Enter> to continue ... "
    read x
    echo "killing yad and tail ..."
    kill $yad_pid
    wait $yad_pid 2>/dev/null
}

error() {
    echo "Error: $*" >&2
    exit 3
}

clean_up() {
    test -e $FIFO     && rm -f $FIFO
    test -d $WORK_DIR && rmdir $WORK_DIR
    unflock $LOCK_FILE
}

main "$@"
