#!/usr/bin/env bash
#
# install-mod.sh
# Downloads a tModLoader Workshop mod by ID, installs the .tmod file,
# enables it in enabled.json (without clobbering already-enabled mods),
# fixes ownership, and restarts the terraria service.
#
# Usage: sudo ./install-mod.sh <workshop_id>
# Example: sudo ./install-mod.sh 2824688072

set -euo pipefail

# Debian/Ubuntu's steamcmd package installs to /usr/games, which isn't part
# of sudo's default secure_path — make sure it's found regardless.
export PATH="${PATH}:/usr/games"

TMODLOADER_APP_ID="1281930"
TERRARIA_USER="terraria"
MODS_DIR="/home/${TERRARIA_USER}/.local/share/Terraria/tModLoader/Mods"
ENABLED_JSON="${MODS_DIR}/enabled.json"
WORKSHOP_CONTENT_DIR="/root/.steam/steam/steamapps/workshop/content/${TMODLOADER_APP_ID}"

if [[ $EUID -ne 0 ]]; then
    echo "This script must be run as root. Try: sudo ./install-mod.sh <workshop_id>" >&2
    exit 1
fi

if [[ $# -ne 1 ]]; then
    echo "Usage: sudo ./install-mod.sh <workshop_id>" >&2
    echo "Example: sudo ./install-mod.sh 2824688072" >&2
    exit 1
fi

WORKSHOP_ID="$1"

if ! [[ "${WORKSHOP_ID}" =~ ^[0-9]+$ ]]; then
    echo "ERROR: workshop_id must be numeric (e.g. 2824688072)." >&2
    exit 1
fi

if [[ ! -d "${MODS_DIR}" ]]; then
    echo "ERROR: ${MODS_DIR} doesn't exist. Is the tModLoader server installed and has it run at least once?" >&2
    exit 1
fi

echo "==> Checking for steamcmd..."
if ! command -v steamcmd &>/dev/null; then
    echo "==> steamcmd not found — installing it now..."
    if ! command -v add-apt-repository &>/dev/null; then
        apt update
        apt install -y software-properties-common
    fi
    add-apt-repository multiverse -y
    dpkg --add-architecture i386
    apt update
    # steamcmd's license prompt normally requires interactive acceptance;
    # this pre-seeds acceptance so the install doesn't hang waiting for input.
    echo steam steam/question select "I AGREE" | debconf-set-selections
    echo steam steam/license note '' | debconf-set-selections
    DEBIAN_FRONTEND=noninteractive apt install -y steamcmd
fi

echo "==> Installing jq (needed to safely edit enabled.json)..."
apt install -y jq

echo "==> Downloading Workshop item ${WORKSHOP_ID} (tModLoader app ${TMODLOADER_APP_ID})..."
steamcmd +login anonymous +workshop_download_item "${TMODLOADER_APP_ID}" "${WORKSHOP_ID}" +quit

ITEM_DIR="${WORKSHOP_CONTENT_DIR}/${WORKSHOP_ID}"

if [[ ! -d "${ITEM_DIR}" ]]; then
    echo "ERROR: Download didn't produce ${ITEM_DIR}. Check the workshop ID is correct and public." >&2
    exit 1
fi

# Workshop mods sometimes ship .tmod files nested under per-tModLoader-version
# subfolders instead of sitting directly in the item folder. Search recursively
# and grab the newest one so we don't accidentally pick an older build.
mapfile -t TMOD_FILES < <(find "${ITEM_DIR}" -name "*.tmod" -printf '%T@ %p\n' | sort -rn | awk '{ $1=""; print substr($0,2) }')

if [[ ${#TMOD_FILES[@]} -eq 0 ]]; then
    echo "ERROR: No .tmod file found under ${ITEM_DIR}." >&2
    exit 1
fi

INSTALLED_NAMES=()

# Deduplicate by filename, keeping the most recently modified copy of each.
declare -A SEEN
for f in "${TMOD_FILES[@]}"; do
    fname=$(basename "${f}")
    if [[ -n "${SEEN[${fname}]:-}" ]]; then
        continue
    fi
    SEEN["${fname}"]=1
    echo "==> Installing ${fname}..."
    cp "${f}" "${MODS_DIR}/${fname}"
    INSTALLED_NAMES+=("${fname%.tmod}")
done

echo "==> Fixing ownership..."
chown -R "${TERRARIA_USER}:${TERRARIA_USER}" "${MODS_DIR}"

echo "==> Updating enabled.json..."
if [[ ! -f "${ENABLED_JSON}" ]] || [[ ! -s "${ENABLED_JSON}" ]]; then
    echo "[]" > "${ENABLED_JSON}"
fi

TMP_JSON=$(mktemp)
CURRENT=$(cat "${ENABLED_JSON}")
NEW="${CURRENT}"
for name in "${INSTALLED_NAMES[@]}"; do
    NEW=$(echo "${NEW}" | jq --arg n "${name}" 'if index($n) then . else . + [$n] end')
done
echo "${NEW}" | jq '.' > "${TMP_JSON}"
mv "${TMP_JSON}" "${ENABLED_JSON}"
chown "${TERRARIA_USER}:${TERRARIA_USER}" "${ENABLED_JSON}"

echo "==> enabled.json now contains:"
cat "${ENABLED_JSON}"

echo "==> Restarting terraria service..."
systemctl restart terraria

echo
echo "==> Done. Installed and enabled: ${INSTALLED_NAMES[*]}"
echo "==> Tailing logs — Ctrl+C to stop watching (server keeps running):"
sleep 2
journalctl -u terraria -n 30 --no-pager
