#!/usr/bin/env bash
# Copyright (c) 2021-2025 community-scripts ORG
# Author: GitHub Copilot
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: https://github.com/hcengineering/huly-selfhost

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

REPO_URL="https://github.com/hcengineering/huly-selfhost.git"

msg_info "Installing Dependencies"
$STD apt-get update
$STD apt-get install -y curl git ca-certificates gnupg nginx python3 python3-venv python3-pip nodejs npm jq build-essential
msg_ok "Installed Dependencies"

msg_info "Cloning Huly repository"
$STD git clone "$REPO_URL" /opt/huly-selfhost
cd /opt/huly-selfhost || exit 1
msg_ok "Cloned Huly repository"

msg_info "Setup uv"
setup_uv
msg_ok "Setup uv"

msg_info "Setting up Python environment"
$STD uv venv venv
if [ -f requirements.txt ]; then
    $STD uv pip install --python venv/bin/python -r requirements.txt
fi
msg_ok "Python environment ready"

msg_info "Setting up Node.js dependencies (if needed)"
if [ -f package.json ]; then
    $STD npm install --omit=dev || true
fi
msg_ok "Node.js dependencies ready"

msg_info "Configuring Huly"
if [ -f config.sh ]; then
    $STD ./config.sh
fi
msg_ok "Huly configured"

msg_info "Configuring nginx"
# Create our own nginx configuration
cat <<EOF >/etc/nginx/sites-available/huly.conf
server {
    listen 80;
    server_name _;
    
    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }
}
EOF

# Enable the site
$STD ln -sf /etc/nginx/sites-available/huly.conf /etc/nginx/sites-enabled/huly.conf

# Test nginx configuration before reloading
if nginx -t >/dev/null 2>&1; then
    $STD nginx -s reload
else
    msg_error "nginx configuration test failed, skipping reload"
fi
msg_ok "nginx configured"

msg_info "Creating systemd service for Huly"
cat <<EOF >/etc/systemd/system/huly.service
[Unit]
Description=Huly Web Service
After=network.target

[Service]
WorkingDirectory=/opt/huly-selfhost
ExecStart=/usr/bin/python3 -m http.server 8080
Restart=always
User=root

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now huly
msg_ok "Created and started Huly service"

motd_ssh
customize

msg_info "Cleaning up"
$STD apt-get -y autoremove
$STD apt-get -y autoclean
msg_ok "Cleaned"

echo -e "${INFO}${YW} Your Huly instance is now running!${CL}"
echo -e "${INFO}${YW} Access it at: http://$(hostname -I | awk '{print $1}')${CL}"
echo -e "${INFO}${YW} For additional configuration, see /opt/huly-selfhost and the official docs.${CL}"
