#!/bin/bash

# Usage:
# scrun instancename command

# - If instancename doesnt exist, starts a screen with instancename and executes the given command.
# - Does not run if the instance is already running.
# - Runs in the same context as a shell (loads environment variables).
# - Logs output into /var/log/scrun/instance/DATE.log, with rotation

# bash -l -c "$@"

# Based on https://gist.github.com/camperdave/980040
echo "defshell -bash" > ~/.screenrc
echo "startup_message off" >> ~/.screenrc
echo "vbell off" >> ~/.screenrc
echo "deflogin on" >> ~/.screenrc
echo "defscrollback 10000" >> ~/.screenrc
echo "defutf8 on" >> ~/.screenrc
echo "defflow off" >> ~/.screenrc
echo "msgwait 20" >> ~/.screenrc
echo "term screen-256color-bce" >> ~/.screenrc

#SCREENNAME=scrun_$1_
SCREENNAME=$1

screen -wipe 2>/dev/null >/dev/null

if ! screen -list | grep -q $SCREENNAME; then
        cesc="${@:2}" # Everything but first one
#       cesc="${cesc@Q}" # Escape it
        screen -dmS $SCREENNAME python3 /data/openpilot/system/clearpilot/tools/faketty.py bash -l -c "$cesc"
        echo screen -dmS $SCREENNAME python3 /data/openpilot/system/clearpilot/tools/faketty.py bash -l -c "$cesc"
#       screen -dmS $1 "$@"
else
       echo $SCREENNAME is already running
fi
