#!/bin/bash

DEFAULT_INSTALLER_PATH="/usr/share/onixos/installer"
DEFAULT_CONFNAME="onixos_configuration"
DEFAULT_CREDNAME="onixos_credentials"


show_help() {
    local lang_code="${LANG:0:2}"
    local lang_file="/usr/share/onixos/installer/lang/${lang_code}.help"

    if [[ ! -f "$lang_file" ]]; then
        lang_file="/usr/share/onixos/installer/lang/en.help"
    fi

    if [[ ! -f "$lang_file" ]]; then
        echo "-----------------------------------------------------------"
        echo "OnixOS Installer (with archinstall)"
        echo "-----------------------------------------------------------"
        echo "Usage: $0 <option>"
        echo "-----------------------------------------------------------"
        echo "- help                            | Show help menu"
        echo "- install                         | Install with default settings"
        echo "- custom <path> [config] [creds]  | Install with custom settings"
        echo "-----------------------------------------------------------"
        return
    fi

    cat "$lang_file"
}


run_archinstall() {
    local path="$1"
    local conf="${2:-$DEFAULT_CONFNAME}"
    local creds="${3:-$DEFAULT_CREDNAME}"

    if [ ! -d $path ]; then
        echo "Error: $path not found."
        return
    fi

    echo "Config: $path/$conf.json"
    echo "Credentials: $path/$creds.json"
    archinstall --config "$path/$conf.json" --creds "$path/$creds.json"
}

if ! command -v archinstall &> /dev/null; then
    echo "Error: 'archinstall' not found."
    exit 1
fi

case "$1" in
    install)
        run_archinstall "$DEFAULT_INSTALLER_PATH"
        ;;
    custom)
        if [[ -z "$2" ]]; then
            echo "Error: 'custom' path required."
            exit 1
        fi
        run_archinstall "$2" "$3" "$4"
        ;;
    help | "")
        show_help
        ;;
    *)
        $0 install
        exit 1
        ;;
esac
