#!/bin/bash
# One entry point for installed MoonBot instances; never starts a trading process without a command.
set -eu

units=()
directories=()
while read -r unit rest; do
    [[ $unit == moonbot@?*.service ]] || continue
    directory=$(systemctl show --value -p WorkingDirectory "$unit")
    units+=("$unit")
    directories+=("$directory")
done < <({ systemctl list-unit-files 'moonbot@*.service' --no-legend --no-pager;
           systemctl list-units 'moonbot@*.service' --all --plain --no-legend --no-pager;
         } | awk '{print $1}' | sort -u)

print_instance() {
    local index=$1
    shift
    printf '  %s  %s\n' "${units[index]}" "${directories[index]}"
    printf '    '
    if (( EUID != 0 )); then printf 'sudo '; fi
    printf '%q ' mb "${units[index]}" "$@"
    printf '\n'
}

list_instances() {
    if (( ${#units[@]} == 0 )); then
        echo 'No MoonBot services are installed.'
    else
        for i in "${!units[@]}"; do print_instance "$i" "$@"; done
    fi
}

prefix=''
if (( $# )) && [[ $1 != --* ]]; then prefix=$1; shift; fi
(( $# )) || set -- --help
if [[ -z $prefix && $1 == --help ]] && (( $# == 1 )); then
    echo 'Usage: mb [service-prefix] --help|--logs|--moonProtoKey|--update VERSION'
    echo '       mb [service-prefix] --setup-moonproto --host IP --port PORT [--rotate-key]'
    echo '       mb [service-prefix] --exchanges|--exchange NAME|--set-api-keys|--retry-login|--status'
    echo 'moonbot is the same command. Without a prefix, run it in the instance directory.'
    echo 'Commands below assume a root shell. From another account, use sudo.'
    echo 'Examples: mb root-Binance --logs; moonbot root-Binance --update MoonBot-L4'
    echo '          mb root-Binance --update release; mb --help'
    list_instances --help
    exit 0
fi
selected=()
for i in "${!units[@]}"; do
    if [[ -n $prefix ]]; then
        if [[ ${units[i]} == "$prefix" ]]; then
            selected=("$i")
            break
        fi
        instance=${units[i]#moonbot@}
        instance=${instance%.service}
        printf -v decoded '%b' "$instance"
        if [[ $instance == "$prefix"* || $decoded == "$prefix"* || ${units[i]%.service} == "$prefix"* ]]; then
            selected+=("$i")
        fi
    elif [[ ${directories[i]} == "$(pwd -P)" ]]; then
        selected+=("$i")
    fi
done

if (( ${#selected[@]} != 1 )); then
    if (( ${#selected[@]} > 1 )); then
        echo 'More than one MoonBot service matches. Use a longer prefix:' >&2
        for i in "${selected[@]}"; do print_instance "$i" "$@" >&2; done
    else
        echo 'No matching MoonBot service. Specify a service prefix or enter its directory.' >&2
        list_instances "$@" >&2
    fi
    exit 1
fi

if (( EUID != 0 )); then
    echo 'MoonBot instance commands require root. Run:' >&2
    print_instance "${selected[0]}" "$@" >&2
    exit 1
fi

directory=${directories[selected[0]]}
if [[ ! -x $directory/MoonBot ]]; then
    echo 'Cannot access this MoonBot executable. Check its path and permissions.' >&2
    exit 1
fi
if [[ ! -f $directory/mb ]]; then
    echo 'This instance predates service commands. Install a current Linux package first.' >&2
    exit 1
fi
exec "$directory/MoonBot" "$@"
