#!/bin/sh
# Factorio options-and-setup frontend, overrides native -s, -m
# to mean server and multiplayer-client startup
# makes default startup reload last local game, pass a bare `-` to not
graphics=${graphics-high} gameopts=() annotopts=()
loadlatest=1; for f; do case $f in
	- | --create | --load-game | --benchmark* | --mp-connect \
		| --start-server* | --map2scenario | --scenario2map )
	loadlatest=0 ;;  # also see below
esac; done
findgame() {
	# set any prefix/version/server path before asking for a game pattern
	local saves=${prefix-$HOME/.factorio$version$serverpath}/saves
	[[ ! -r $1 && $1 != */* ]] \
		&& set -- "`find "$saves" -iname "*$1*" -exec ls -t {} + |sed q`"
	[[ -r $1 ]] && loadlatest=0
	printf %s "$1"
}
while getopts :h?-:G:g:snp:qCc:xvVNmM:b:0123456789.t: opt; do case $opt in
	#*) [[ $- == *x* ]] && echo $OPTIND'*'$opt'*'$OPTARG ;;&
	[gmbnhC:]) loadlatest=0 ;;&  # want no-arg `-` to be `-n` equiv
	V) mods=vanilla ;;
	M) mods=$OPTARG ;;
	g) gameopts+=(--load-game "`findgame "$OPTARG"`") ;;
	m) gameopts+=(--mp-connect 127.0.0.1) ;;
	s) serverpath=/server ;;
	b) gameopts+=(--benchmark "`findgame "$OPTARG"`" --disable-audio) graphics=very-low;;
	t) gameopts+=(--benchmark-ticks "$OPTARG") ;;
	G) graphics=$OPTARG ;;
	p) prefix=$OPTARG ;;
	x) set -x ;;
	c) config=$OPTARG ;;
	C) updateopt=d@0 loadlatest=0 ;;
	N) annotate= ;;
	q) annotopts+=(quiet=1) ;;
	# overcomplicated version-picker option parsing:
	[0-3]) version=${version-/}$opt ;;
	[4-9]) version=${version-/1}$opt ;;
	.) version=${version-/17}$opt;;
	# `--` stops frontend option processing, all long options passed along to
	# game engine, `--help` is processed by both frontend and engine
	"-") ((--OPTIND)); [[ $OPTARG = help  ]] && sed /^$/Q "$0"; break ;;
	# and `-h` is passed along too because that works well enough
	h|\?) sed '/^$/Q' "$0"; gameopts+=(-h) ;;
	v) gameopts+=(-v)
esac; done; shift $((OPTIND-1))

prefix=${prefix-$HOME/.factorio}$version$serverpath
[[ -z $mods ]] || {
	[[ $mods = */* ]] || mods=$prefix/mods.$mods
	gameopts+=(--mod-directory "$mods")
	mkdir -p "$mods"
}

(( loadlatest && $# == 1 )) && [[ $1 != -* ]] && {
	[[ -z $serverpath ]] && gameopts+=(--load-game) || gameopts+=(--start-server)
	gameopts+=("`findgame "$1"`")
	loadlatest=0
}

config=${config-$prefix/config/config.ini}

[[ -r $config ]] || cat <<-EOD >$config
	[path]
	read-data=__PATH__executable__/../../data
	write-data=$prefix
	[other]
	$([[ ${version:-/16} < /16 ]] || echo non-blocking-saving=true)
	EOD

[[ $version > /14 ]] && {
	config_graphics=`awk -F= '$1~/graphics-quality/{print $2}' "$config"`
	[[ ${config_graphics:-$graphics} != $graphics ]] &&
		gameopts+=(--graphics-quality $graphics)
}

updatecheck=$prefix/config/last_update_check

[[ $- == *x* ]] && declare -p | awk '$3!~/^[A-Z]/'

[[ $prefix = ~/.factorio ]] && {
	# ordinarily try to keep the update checks down to every 8 hours
	touch -${updateopt-a} $updatecheck
	since_last_check=$((`date +%s`-`stat -c%Y $updatecheck`))
	if (( since_last_check > 8*3600 ))
	then	touch $updatecheck
		sed -ri 's|^[ ;]*(check-updates)\s*=.*|\1=true|' $config
	else
		sed -ri 's|^[ ;]*(check-updates)\s*=.*|\1=false|' $config
	fi
}

# default to just restart where we left off
((loadlatest)) && {
	lastgame=$(find "$prefix/saves" -type f -exec ls -t {} + | sed q)
	[[ -n $lastgame ]] && {
		[[ -z $serverpath ]] && gameopts+=(--load-game) || gameopts+=(--start-server)
		gameopts+=("$lastgame")
	}
}

if [[ -r ${annotate=`echo "$prefix"/mods/Benchmark*/annotate-log.awk`}  ]]; then
	rlwrap -C Factorio -m -M .lua -r $prefix/bin/x64/factorio -c $config "${gameopts[@]}" "$@" \
	| $annotate "${annotopts[@]}"
else
	exec rlwrap -C Factorio -m -M .lua -r $prefix/bin/x64/factorio -c $config "${gameopts[@]}" "$@"
fi
