#!/usr/bin/env bash
source <(curl -fsSL https://git.bila.li/Proxmox/proxmox-ve-install-scripts/raw/branch/dev/misc/build.func)
# 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/Dictionarry-Hub/profilarr

# App Default Values
APP="profilarr"
var_tags="${var_tags:-arr}"
var_cpu="${var_cpu:-2}"
var_ram="${var_ram:-2048}"
var_disk="${var_disk:-8}"
var_os="${var_os:-debian}"
var_version="${var_version:-12}"
var_unprivileged="${var_unprivileged:-1}"

header_info "$APP"
variables
color
catch_errors

function update_script() {
    header_info
    check_container_storage
    check_container_resources

    # Check if installation is present
    if [[ ! -d /opt/${APP}/backend ]]; then
        msg_error "No ${APP} Installation Found!"
        exit
    fi
    setup_uv
    # Crawling the new version and checking whether an update is required
    RELEASE=$(curl -fsSL https://api.github.com/repos/Dictionarry-Hub/profilarr/releases/latest | grep "tag_name" | cut -d'"' -f4)
    if [[ -z "$RELEASE" ]]; then
        msg_error "Failed to fetch latest release version"
        exit 1
    fi
    if [[ -f /opt/${APP}_version.txt ]] && [[ "${RELEASE}" == "$(cat /opt/${APP}_version.txt)" ]]; then
        msg_ok "No update required. ${APP} is already at ${RELEASE}"
        exit
    fi

    # Stopping Services
    msg_info "Stopping $APP"
    systemctl stop ${APP}
    msg_ok "Stopped $APP"

    # Creating Backup
    msg_info "Creating Backup"
    if ls /opt/"${APP}"_backup_*.tar.gz &>/dev/null; then
        rm -f /opt/"${APP}"_backup_*.tar.gz
        msg_info "Removed previous backup"
    fi
    tar -czf "/opt/${APP}_backup_$(date +%F).tar.gz" /opt/${APP} /opt/${APP}_config
    msg_ok "Backup Created"

    # Execute Update
    msg_info "Updating $APP to v${RELEASE}"
    temp_file=$(mktemp)
    curl -fsSL -o "$temp_file" "https://github.com/Dictionarry-Hub/profilarr/archive/refs/tags/${RELEASE}.zip"
    unzip -q -o "$temp_file" -d /tmp

    # Find the actual extracted directory name
    EXTRACTED_DIR=$(find /tmp -maxdepth 1 -name "profilarr-*" -type d | head -n1)
    if [[ -z "$EXTRACTED_DIR" ]]; then
        msg_error "Failed to find extracted directory"
        exit 1
    fi

    rm -rf /opt/${APP}/backend /opt/${APP}/frontend
    mv "${EXTRACTED_DIR}/backend" /opt/${APP}/
    mv "${EXTRACTED_DIR}/frontend" /opt/${APP}/

    # Update Python dependencies
    msg_info "Updating Python dependencies"
    cd /opt/${APP}/backend || exit

    # Create a temporary requirements file excluding the incompatible PyYAML version
    temp_req_file=$(mktemp)
    grep -v "^PyYAML" requirements.txt >"$temp_req_file"

    if [[ -f "/opt/${APP}/.requirements_checksum" ]]; then
        CURRENT_CHECKSUM=$(md5sum "$temp_req_file" | awk '{print $1}')
        STORED_CHECKSUM=$(cat /opt/${APP}/.requirements_checksum)
        if [[ "$CURRENT_CHECKSUM" != "$STORED_CHECKSUM" ]]; then
            msg_info "Requirements have changed. Performing full upgrade."
            # Ensure compatible PyYAML is installed
            $STD uv pip install --python /opt/${APP}/venv/bin/python "PyYAML>=6.0"
            $STD uv pip install -r "$temp_req_file" --python /opt/${APP}/venv/bin/python
        else
            msg_info "Requirements unchanged. Verifying installation."
            $STD uv pip install -r "$temp_req_file" --python /opt/${APP}/venv/bin/python
        fi
    else
        # Ensure compatible PyYAML is installed
        $STD uv pip install --python /opt/${APP}/venv/bin/python "PyYAML>=6.0"
        $STD uv pip install -r "$temp_req_file" --python /opt/${APP}/venv/bin/python
    fi
    md5sum "$temp_req_file" | awk '{print $1}' >/opt/${APP}/.requirements_checksum
    rm -f "$temp_req_file"
    msg_ok "Updated Python dependencies"

    # Build frontend
    msg_info "Building Frontend"
    cd /opt/${APP}/frontend || exit
    npm install
    npm run build
    cp -r dist/* /opt/${APP}/backend/app/static/
    msg_ok "Built Frontend"

    # Starting Services
    msg_info "Starting $APP"
    systemctl start ${APP}
    msg_ok "Started $APP"

    # Cleaning up
    msg_info "Cleaning Up"
    rm -f "$temp_file"
    rm -rf "$EXTRACTED_DIR"
    msg_ok "Cleanup Completed"

    # Last Action
    echo "${RELEASE}" >/opt/${APP}_version.txt
    msg_ok "Updated $APP to v${RELEASE}"
    exit
}

start
build_container
description

msg_ok "Completed Successfully!\n"
echo -e "${CREATING}${GN}${APP} setup has been successfully initialized!${CL}"
echo -e "${INFO}${YW} Access it using the following URL:${CL}"
echo -e "${TAB}${GATEWAY}${BGN}http://${IP}:6868${CL}"
