#!/usr/bin/env bash
set -euo pipefail

origin='github.com/bottlesdevs/bottles'
cpak_bin="${BOTTLES_CPAK_BIN:-/usr/bin/cpak}"
data_home="${XDG_DATA_HOME:-$HOME/.local/share}"
state_dir="${XDG_STATE_HOME:-$HOME/.local/state}/bottles-office-experimental"
bottles_dir="$data_home/bottles"
word="$bottles_dir/bottles/Office/drive_c/Program Files/Microsoft Office/root/Office16/WINWORD.EXE"
helper="$bottles_dir/.office-experimental-installer.py"
runner_root="${BOTTLES_SODA_RUNNERS_ROOT:-/usr/libexec/bottles-soda-experimental}"
umask 077
mkdir -p -- "$state_dir"
log="$state_dir/install.log"

log_message() { printf '[%s] %s\n' "$(date -Is)" "$*" | tee -a "$log"; }
log_output() {
    local line
    while IFS= read -r line || [[ -n "$line" ]]; do
        printf '[%s] %s\n' "$(date -Is)" "$line" | tee -a "$log"
    done
}
run_logged() {
    local status
    set +e
    "$@" 9>&- 2>&1 | log_output 9>&-
    status=${PIPESTATUS[0]}
    set -e
    return "$status"
}
fail() { log_message "ERROR: $*" >&2; return 1; }

choose_edition() {
    local choice="${1:-}"
    if [[ -z "$choice" ]]; then
        [[ -t 0 ]] || { fail 'Specify business or enterprise without an interactive terminal.'; return 2; }
        printf '%s\n' 'Microsoft 365 edition:' '  1) Business' '  2) Enterprise' >&2
        printf 'Choose [1-2]: ' >&2
        IFS= read -r choice || return 1
    fi
    case "$choice" in
        1|business) printf 'business\n' ;;
        2|enterprise) printf 'enterprise\n' ;;
        *) fail 'Expected business or enterprise.'; return 2 ;;
    esac
}

install_office() {
    local edition="$1" runner
    runner="$(find "$runner_root" -mindepth 1 -maxdepth 1 -type d \
      -name 'soda-*-experimental' -printf '%f\n' 2>/dev/null | LC_ALL=C sort -V | tail -n 1)"
    [[ -n "$runner" ]] || { fail 'No packaged experimental Soda runner is installed.'; return 1; }
    [[ -x "$cpak_bin" ]] || { fail "CPak executable missing: $cpak_bin"; return 1; }
    if [[ -f "$word" && -s "$state_dir/edition" ]]; then
        if [[ "$(<"$state_dir/edition")" == "$edition" ]]; then
            log_message 'Microsoft 365 is already installed.'
            return 0
        fi
        fail 'A different Office edition is already installed in the Office bottle.'
        return 1
    fi

    exec 9>"$state_dir/lock"
    if ! flock -n 9; then
        fail 'An Office installation is already running. Do not start a second one.'
        return 1
    fi
    if ! run_logged bottles-cpak install; then
        fail 'Unable to install Bottles into the user CPak store.'
        return 1
    fi
    if ! run_logged bottles-soda-import; then
        fail 'Unable to import the experimental Soda runner.'
        return 1
    fi
    if [[ ! -x "$bottles_dir/runners/$runner/bin/wine" ]]; then
        fail "The expected runner $runner is missing after import."
        return 1
    fi
    if [[ -s "$state_dir/requested-edition" && "$(<"$state_dir/requested-edition")" != "$edition" ]]; then
        fail 'A previous unfinished installation selected another Office edition.'
        return 1
    fi
    install -Dm0644 "${BOTTLES_OFFICE_HELPER:-/usr/share/bottles-office-experimental/office-install.py}" "$helper"
    printf '%s\n' "$edition" > "$state_dir/requested-edition"
    log_message "Installing Microsoft 365 $edition with $runner in a separate CPak instance."
    if ! run_logged "$cpak_bin" run --instance bottles-office-setup "$origin" @python3 "$helper" "$edition" "$runner"; then
        fail "Office installation failed. See $log. If an older Office instance is still active, stop it explicitly before retrying."
        return 1
    fi
    if [[ ! -f "$word" ]]; then
        fail 'The installer completed but Microsoft Word was not found.'
        return 1
    fi
    printf '%s\n' "$edition" > "$state_dir/edition"
    log_message 'Microsoft 365 installation completed.'
}

case "${1:-help}" in
    help|-h|--help)
        printf '%s\n' 'Usage: bottles-office-experimental install [business|enterprise] | status'
        ;;
    status)
        if [[ -f "$word" ]]; then printf 'Office files found: %s\n' "$word"; else printf 'Office is not installed. Log: %s\n' "$log"; fi
        ;;
    install)
        [[ "$(id -u)" != 0 ]] || { fail 'Run as your normal user, not as root.'; exit 1; }
        (( $# <= 2 )) || { fail 'Unexpected arguments.'; exit 2; }
        choice="$(choose_edition "${2:-}")" || exit $?
        install_office "$choice"
        ;;
    *) fail 'Unknown command. Use install or status.'; exit 2 ;;
esac
