#!/usr/bin/env bash

# Copyright (c) 2021-2026 tteck
# Author: tteck
# Co-Author: MickLesk (Canbiz)
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: https://github.com/msgbyte/tianji

source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
color
verb_ip6
catch_errors
setting_up_container
network_check
update_os

msg_info "Installing Dependencies"
$STD apt install -y \
  python3 \
  cmake \
  build-essential \
  git
msg_ok "Installed Dependencies"

NODE_VERSION="22" NODE_MODULE="pnpm@$(curl -s https://raw.githubusercontent.com/msgbyte/tianji/master/package.json | jq -r '.packageManager | split("@")[1]')" setup_nodejs
PG_VERSION="17" setup_postgresql
PG_DB_NAME="tianji_db" PG_DB_USER="tianji" setup_postgresql_db
PYTHON_VERSION="3.13" setup_uv
fetch_and_deploy_gh_release "tianji" "msgbyte/tianji" "tarball"
TIANJI_SECRET=$(openssl rand -base64 256 | tr -dc 'A-Za-z' | head -c 64)
echo "Tianji Secret: $TIANJI_SECRET" >>~/tianji.creds

msg_info "Setting up Tianji"
cd /opt/tianji
$STD pnpm install --filter @tianji/client... --config.dedupe-peer-dependents=false --frozen-lockfile
$STD pnpm build:static
$STD pnpm install --filter @tianji/server... --config.dedupe-peer-dependents=false
mkdir -p ./src/server/public
cp -r ./geo ./src/server/public
$STD pnpm build:server
cat <<EOF >/opt/tianji/src/server/.env
DATABASE_URL="postgresql://$PG_DB_USER:$PG_DB_PASS@localhost:5432/$PG_DB_NAME?schema=public"
OPENAI_API_KEY=""
JWT_SECRET="$TIANJI_SECRET"
EOF
cd /opt/tianji/src/server
$STD pnpm db:migrate:apply
rm -rf /opt/tianji/src/client
rm -rf /opt/tianji/website
rm -rf /opt/tianji/reporter
msg_ok "Setup Tianji"

msg_info "Setting up AppRise"
$STD uv pip install apprise cryptography --system
msg_ok "Setup AppRise"

msg_info "Creating Service"
cat <<EOF >/etc/systemd/system/tianji.service
[Unit]
Description=Tianji Server
After=network.target

[Service]
ExecStart=/usr/bin/node /opt/tianji/src/server/dist/src/server/main.js
WorkingDirectory=/opt/tianji/src/server
Restart=always
RestartSec=10
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target
EOF
systemctl enable -q --now tianji
msg_ok "Created Service"

motd_ssh
customize
cleanup_lxc
