#!/bin/sh

# If exists tmux session
# If Responds to queries

SERVER_DIR='/home/ubuntu/minecraft'
TMUX_NAME='minecraft server'
LIVE_UNTIL="/home/ubuntu/minecraft/live_until.txt"

json_has() {
    cat - | python3 -c "import sys, json; sys.exit(0 if '$1' in json.load(sys.stdin) else 1)"
}

json_parse() {
    cat - | python3 -c "import sys, json; print(json.load(sys.stdin)['$1'])"
}

silent_exitcode() {
    $* > /dev/null 2>&1
}

extend_ttl() {
    # Extend time to live 30 minutes at a time
    new_ttl="$(date -d '+30 min' +%s)"
    old_ttl="$(date -d "$(cat "$LIVE_UNTIL")" +%s)"
    if [ ! -f "$LIVE_UNTIL" ] || [ "$new_ttl" -ge "$old_ttl" ]; then
        # If LIVE_UNTIL file not existing or new time to live longer
        echo "Extending time to live until $(date -d "@$new_ttl")"
        date -d "@$new_ttl" > "$LIVE_UNTIL"
    fi
    exit 0
}

soft_poweroff() {
    # Poweroff, if time to live has expired
    ttl="0"
    if [ -f "$LIVE_UNTIL" ]; then
        ttl="$(date -d "$(cat "$LIVE_UNTIL")" +%s)"
    fi
    echo "Time to live is $(cat "$LIVE_UNTIL")"
    if [ "$(date +%s)" -ge "$ttl" ]; then
        echo "Server empty longer than grace time, shutting down"
        tmux send-keys -t "$TMUX_NAME.0" "stop" ENTER
        sleep 5
        $(sudo /sbin/shutdown -P +1)
    fi
    exit 1
}

tmux_running() {
    tmux ls -F "#{session_name}" | grep -q "$TMUX_NAME"
}

server_responsive() {
    silent_exitcode /usr/local/bin/mcstatus localhost ping
}

get_nplayers() {
    json="$(/usr/local/bin/mcstatus localhost json)"
    if `echo $json | json_has player_count`; then
        echo $json | json_parse player_count
        return
    fi
    status="$(/usr/local/bin/mcstatus localhost status)"
    echo "$status" | grep players: | sed 's/.*\([0-9]\+\)\/.*/\1/g'
}

n_logins="$(w -h | wc -l)"
echo "$(date) [$n_logins logins]"

if [ "$n_logins" -gt 0 ]; then
    echo "Keep alive as there are active ssh sessions"
    extend_ttl
fi

if tmux_running; then
    : #echo "Tmux running"
else
    echo "Tmux not running"
    soft_poweroff
fi

if server_responsive; then
    n_players=$(get_nplayers)
    echo "Server responsive. $n_players players online"
    if [ "$n_players" -gt 0 ]; then
        # Keep alive as players are online
        extend_ttl
    else
        soft_poweroff
    fi
else
    echo "Server unresponsive"
    soft_poweroff
fi
