#!/usr/bin/env bash

# Enable unofficial strict mode
set -e # Exit immediately if any command exits with non-zero status;
       # use `cmd || cmd2` if `cmd` must fail, `cmd || true` if it may fail
set -u # Reading a variable not previously defined raises an error
set -o pipefail # if a cmd in the pipeline fails, its return status is the whole pipeline return status
IFS=$'\n\t' # internal field separator
# remember to use `trap (cleanup_function) EXIT` for cleanup. To remove trap, use `-` as cleanup_function
# use `local` for local variables
# use `readonly` for constants, `local -r` for scoped constants

function get_conf_file {
    for path in "/etc/standard-raspberry/conf.toml" "/etc/ipsum/conf.toml";
    do
        if [[ -e "${path}" ]];
        then
            echo "${path}"
            return 0
        fi
    done
    echo "Running on a device without a conf file" >&2
    exit 1
}

function config() {
    local -r conf="$(get_conf_file)"
    case $1 in
        nano|"")
            sudo nano "${conf}" ;;
        vim|v)
            sudo -E vim "${conf}" ;;
        nvim|n)
            sudo -E nvim "${conf}" ;;
        cat|c)
            cat "${conf}" ;;
        less|l)
            less "${conf}" ;;
        *)
            echo "Invalid command $1" ;;
    esac
}

program=""
if [[ $# -ge 1 ]];
then
    program="${1}"
fi
config "${program}"
