#!/usr/bin/bash

# heos-login  Copyright 2025-2026  Norman Carver

# Script program to login a HEOS device to a HEOS account.
#
# This should be necessary only if the device has not been
# addressed from the HEOS app since rebooting.
#
# Logs in the default Master HEOS device by default, but can select alternative.
# Alternative device must be specified by its IPNUM (last quad of its IP address).
#
# Will be prompted for account info if not setup in heosinfo-account file.


function print_usage()
{
    echo -e "Login a HEOS Device to a HEOS account." >&2
    echo -e "(Logs in the default Master HEOS device by default.)\n" >&2
    echo    "Usage: heos-login [DEVICE_IPNUM]" >&2
    echo    "where:" >&2
    echo    "  DEVICE_IPNUM -- IPNUM of HEOS device to login;" >&2
    echo    "  (IPNUM means the last quad of an IP address only: i.e., 0--255.)" >&2
}


if [[ "$1" == --help ]]; then
    print_usage
    exit 0
fi

# Catch invalid supplied options:
debugopt=""
while [[ "$1" == -* ]]; do
    if [[ "$1" == -- ]]; then
        shift;break
    elif [[ "$1" == --debug ]]; then
        debugopt=--debug
    else
        echo "Error: invalid option '$1'" >&2
        echo "(use '--' to signal end of options, with -* arguments)" >&2
        exit 1 
    fi
done

# Process command arguments:
if [[ $# -gt 1 ]]; then
    print_usage
    exit 1
fi

if [[ $# == 1 ]]; then
    device=$1
else
    device=""
fi
heosdir=$(dirname "$0")


# Get HEOS account info from file if available:
heosuser=""
heospwd=""
if [[ -f "$heosdir"/heosutils/heosinfo-account ]]; then
    source "$heosdir"/heosutils/heosinfo-account
fi

# Prompt user for HEOS username and passwd, if missing:
if [[ -z "$heosuser" ]]; then
    read -e -p "Enter HEOS Email/Username: " heosuser
fi
if [[ -z "$heospwd" ]]; then
    IFS= read -e -s -p "Enter HEOS Password: " heospwd
fi


# heosutil-run-command error checking function (two json outputs):
# args: 1) command result variable; 2) error message; [3) error action]
# (default action on error is 'exit 1', use $3 of 'return 1' to continue execution)
function error_check_run_command_2json()
{
    cmdresult=${!1}
    if [[ ($? != 0) || ("$cmdresult" != *'"result": "success"'*'"result": "success"'*) ]]; then
        if [[ "$cmdresult" == Error:* || ($debugopt == --debug && "$cmdresult" == ERROR:*) ]]; then
            echo "$cmdresult" >&2
        fi
        if [[ -n "$2" ]]; then echo "$2" >&2; fi
        if [[ $# == 3 ]]; then $3; else exit 1; fi
    else
        return 0
    fi
}


# Login (and activate) device:
loggedin=false
numtries=3
while [[ $numtries -gt 0 ]]; do
    # Login device:
    result=$("$heosdir"/heosutils/heosutil-run-command --numjson=2 "heos://system/sign_in?un=${heosuser}&pw=${heospwd}" $device 2>/dev/null)
    if error_check_run_command_2json result "" "return 1"; then
        loggedin=true
        break
    fi
    numtries=$((numtries-1))
done

if ! $loggedin; then
    echo;echo "Error: Login FAILED!" >&2
    exit 1
fi

#EOF
