#!/bin/bash

set -e

CRONTAB_USER="root"
CRONTAB_FILE="/tmp/new_crontab"

cleanup() {
    if [ -f "$CRONTAB_FILE" ]; then
        rm -f "$CRONTAB_FILE"
    fi
}
trap cleanup EXIT

error_handler() {
    renv set software_update_set_auto_upgrade_config_status fail
    cleanup
    exit 1
}
trap error_handler ERR

if [ "$(id -u)" != "0" ]; then
    echo "Error: This script must be run as root" >&2
    exit 1
fi

if ! [ -w "/etc/apt/apt.conf.d" ]; then
    echo "Error: No write permission to /etc/apt/apt.conf.d" >&2
    exit 1
fi

renv set software_update_set_auto_upgrade_config_status running

get_uci_config() {
    local key="$1"
    local value
    value=$(uci get "$key" 2>/dev/null)
    if [ $? -ne 0 ]; then
        # Return empty string if UCI key doesn't exist or has no value, let caller handle default/error
        echo ""
        return 0
    fi
    echo "$value"
}

ROSP_AUTO_UPGRADE=$(get_uci_config software_update.rosp_auto_update_type)
DEBIAN_AUTO_UPGRADE=$(get_uci_config software_update.debian_auto_update_type)
APP_CENTER_AUTO_UPGRADE=$(get_uci_config software_update.app_auto_update_type)
CHECKING_TIME=$(get_uci_config software_update.checking_time)

rosp_repo_config="/etc/apt/sources.list.d/rosp.list"
app_repo_config="/etc/apt/sources.list.d/rosp_app.list"

# Function to parse all valid deb lines from a repository config file
# Outputs each valid entry as "origin archive component" on a new line
parse_repo_config() {
    local config_file="$1"
    local output=""
    
    if [ ! -f "$config_file" ] || [ ! -r "$config_file" ]; then
        echo "Warning: Repository config file '$config_file' does not exist or is not readable." >&2
        # Return empty string, not an error, maybe file doesn't exist yet
        echo ""
        return 0
    fi

    # Process each non-comment, non-empty deb line
    while IFS= read -r line; do
        if [[ -z "$line" ]]; then
            continue
        fi

        local origin=""
        local archive=""
        local component=""
        local url_part=""

        # Extract URL part considering potential options [...]
        if echo "$line" | grep -q "\[.*\]"; then
            url_part=$(echo "$line" | sed -E 's/^deb\s+\[[^]]+\]\s+(\S+).*/\1/')
        else
            url_part=$(echo "$line" | awk '{print $2}')
        fi
        origin=$(echo "$url_part" | sed -E 's#^[^/]+//([^/]+).*$#\1#')
        
        # Extract archive (codename) and component
        # This logic assumes archive is the first word after URL (or options+URL)
        # and component is the word after archive. Handles potential multiple components later.
        local parts_str=$(echo "$line" | sed -E 's/^deb\s+(\[[^]]+\]\s+)?\S+\s+//')
        local parts_arr=($parts_str)
        archive="${parts_arr[0]}"
        component="${parts_arr[1]}" # Take the first component listed for now

        if [ -n "$origin" ] && [ -n "$archive" ] && [ -n "$component" ]; then
             # Append "origin archive component" to the output string, separated by newline
             if [ -z "$output" ]; then
                 output="${origin} ${archive} ${component}"
             else
                 output="${output}\n${origin} ${archive} ${component}"
             fi
        else
            echo "Warning: Failed to parse line in '$config_file': $line" >&2
        fi
    done < <(grep -Ev "^#|^$" "$config_file" | grep "^deb") # Read only valid deb lines

    if [ -z "$output" ]; then
        echo "Warning: No valid deb lines found or parsed in '$config_file'" >&2
    fi

    echo -e "$output" # Use -e to interpret newline characters
}

if [ "$ROSP_AUTO_UPGRADE" = "disable" ] && [ "$DEBIAN_AUTO_UPGRADE" = "disable" ] && [ "$APP_CENTER_AUTO_UPGRADE" = "disable" ]; then
    echo "All auto upgrade types are disabled, cleaning up existing configurations..."
    
    # Remove the cron job for auto upgrades
    crontab -u "$CRONTAB_USER" -l 2>/dev/null | grep -v "/usr/scripts/run_software_auto_upgrades.sh" > "$CRONTAB_FILE" || true
    if [ -s "$CRONTAB_FILE" ]; then
        crontab -u "$CRONTAB_USER" "$CRONTAB_FILE"
    else
        # If crontab becomes empty, remove it entirely
        crontab -u "$CRONTAB_USER" -r 2>/dev/null || true
    fi
    
    # Clear or disable unattended-upgrades configuration
    cat > /etc/apt/apt.conf.d/50unattended-upgrades <<EOF
// Automatically generated by rosp - All auto upgrades disabled

Unattended-Upgrade::Origins-Pattern {
};

Unattended-Upgrade::Package-Blacklist {
};

Unattended-Upgrade::DevRelease "no";
Unattended-Upgrade::Remove-Unused-Dependencies "false";
Unattended-Upgrade::Automatic-Reboot "false";
Unattended-Upgrade::Automatic-Reboot-WithUsers "false";
Unattended-Upgrade::Dl-Limit "0";
Unattended-Upgrade::Mail "";
Unattended-Upgrade::MailOnlyOnError "true";
Unattended-Upgrade::AutoFixInterruptedDpkg "true";
Unattended-Upgrade::Skip-Updates-On-Metered-Connections "false";
Unattended-Upgrade::SyslogEnable "true";
Unattended-Upgrade::SyslogFacility "daemon";
EOF
    
    renv set software_update_set_auto_upgrade_config_status success
    echo "Auto upgrade configurations have been disabled and cleaned up"
    exit 0
fi

# Parse ROS Pro repos
rosp_config_lines=$(parse_repo_config "$rosp_repo_config")
# Parse App Center repos
app_config_lines=$(parse_repo_config "$app_repo_config")

rosp_upgrade_config_entries=""
if [ "$ROSP_AUTO_UPGRADE" = "recommended" ]; then
    while IFS= read -r line; do
        if [ -z "$line" ]; then continue; fi
        read -r origin archive component <<< "$line"
        # If origin starts with debian.robustel., replace it with Robustel
        if [[ "$origin" == debian.robustel.* ]]; then
            origin="Robustel"
        fi
        if [[ "$origin" == *rcms-test.rdmscloud.com* ]]; then
            origin="Robustel"
        fi
        rosp_upgrade_config_entries="${rosp_upgrade_config_entries}\"origin=${origin},archive=${archive},component=${component}\";\n    "
    done <<< "$rosp_config_lines"
elif [ "$ROSP_AUTO_UPGRADE" = "security" ]; then
     while IFS= read -r line; do
        if [ -z "$line" ]; then continue; fi
        read -r origin archive component <<< "$line"
        # If origin starts with debian.robustel., replace it with Robustel
        if [[ "$origin" == debian.robustel.* ]]; then
            origin="Robustel"
        fi
        if [[ "$origin" == *rcms-test.rdmscloud.com* ]]; then
            origin="Robustel"
        fi
        # Check if archive name contains 'bugfix'
        if [[ "$archive" == *bugfix* ]]; then
            rosp_upgrade_config_entries="${rosp_upgrade_config_entries}\"origin=${origin},archive=${archive},component=${component}\";\n    "
        fi
    done <<< "$rosp_config_lines"
fi

# Trim trailing newline and spaces if any entries were added
rosp_upgrade_config_entries=$(echo -e "${rosp_upgrade_config_entries}" | sed '/^[[:space:]]*$/d' | sed '$ s/;//')

debian_upgrade_config_entries=""
if [ "$DEBIAN_AUTO_UPGRADE" = "all" ]; then
    debian_upgrade_config_entries='
    "origin=Debian,archive=*-updates";
    "origin=Debian,archive=*-security";'
elif [ "$DEBIAN_AUTO_UPGRADE" = "security" ]; then
    debian_upgrade_config_entries='"origin=Debian,archive=*-security";'
fi

app_center_upgrade_config_entries=""
if [ "$APP_CENTER_AUTO_UPGRADE" = "all" ]; then
    while IFS= read -r line; do
        if [ -z "$line" ]; then continue; fi
        read -r origin archive component <<< "$line"
        # If origin starts with debian.robustel., replace it with Robustel
        if [[ "$origin" == debian.robustel.* ]]; then
            origin="Robustel"
        fi
        if [[ "$origin" == *rcms-test.rdmscloud.com* ]]; then
            origin="Robustel"
        fi
        app_center_upgrade_config_entries="${app_center_upgrade_config_entries}\"origin=${origin},archive=${archive},component=${component}\";\n    "
    done <<< "$app_config_lines"
elif [ "$APP_CENTER_AUTO_UPGRADE" = "security" ]; then
    while IFS= read -r line; do
        if [ -z "$line" ]; then continue; fi
        read -r origin archive component <<< "$line"
        # If origin starts with debian.robustel., replace it with Robustel
        if [[ "$origin" == debian.robustel.* ]]; then
            origin="Robustel"
        fi
        if [[ "$origin" == *rcms-test.rdmscloud.com* ]]; then
            origin="Robustel"
        fi
        # Check if archive name contains 'bugfix'
        if [[ "$archive" == *bugfix* ]]; then
             app_center_upgrade_config_entries="${app_center_upgrade_config_entries}\"origin=${origin},archive=${archive},component=${component}\";\n    "
        fi
    done <<< "$app_config_lines"
fi

# Trim trailing newline and spaces if any entries were added
app_center_upgrade_config_entries=$(echo -e "${app_center_upgrade_config_entries}" | sed '/^[[:space:]]*$/d' | sed '$ s/;//')


UNATTENDED_UPGRADE_CONFIG=$(cat <<EOF
// Automatically generated by rosp

Unattended-Upgrade::Origins-Pattern {
    ${debian_upgrade_config_entries}
    ${rosp_upgrade_config_entries}
    ${app_center_upgrade_config_entries}
};

Unattended-Upgrade::Package-Blacklist {
};

Unattended-Upgrade::DevRelease "no";

Unattended-Upgrade::Remove-Unused-Dependencies "true";

Unattended-Upgrade::Automatic-Reboot "false";

Unattended-Upgrade::Automatic-Reboot-WithUsers "false";

Unattended-Upgrade::Dl-Limit "0";

Unattended-Upgrade::Mail "";
Unattended-Upgrade::MailOnlyOnError "true";

Unattended-Upgrade::AutoFixInterruptedDpkg "true";
Unattended-Upgrade::Skip-Updates-On-Metered-Connections "false";

Unattended-Upgrade::SyslogEnable "true";
Unattended-Upgrade::SyslogFacility "daemon";
EOF
)

# Ensure there are no blank lines within Origins-Pattern if some sections are empty
# And ensure proper formatting with semicolons
UNATTENDED_UPGRADE_CONFIG=$(echo "$UNATTENDED_UPGRADE_CONFIG" | awk '
    BEGIN {in_pattern=0}
    /Unattended-Upgrade::Origins-Pattern \{/ {print; in_pattern=1; next}
    /^\};/ && in_pattern {
        # Print accumulated non-empty lines, adding semicolon if needed
        gsub(/^[ \t]+|[ \t]+$/, "", accumulated_lines) # Trim whitespace
        sub(/;[ \t]*$/, "", accumulated_lines) # Remove trailing semicolon if present
        if (accumulated_lines != "") {
            print "    " accumulated_lines ";";
        }
        print; in_pattern=0; accumulated_lines=""; next
    }
    in_pattern {
        line = $0;
        gsub(/^[ \t]+|[ \t]+$/, "", line); # Trim leading/trailing whitespace
        if (line != "") {
            # Remove trailing semicolon before accumulating
            sub(/;[ \t]*$/, "", line);
            if (accumulated_lines == "") {
                accumulated_lines = line;
            } else {
                accumulated_lines = accumulated_lines ";\n    " line;
            }
        }
        next # Dont print lines inside pattern block yet
    }
    {print} # Print lines outside the pattern block
')


if ! echo "$UNATTENDED_UPGRADE_CONFIG" > /etc/apt/apt.conf.d/50unattended-upgrades; then
    echo "Error writing to /etc/apt/apt.conf.d/50unattended-upgrades" >&2
    exit 1
fi

# Convert HH:MM time format to cron expression
time_to_cron() {
    local time="$1"
    local hour minute
    
    # Default to 00:00 if CHECKING_TIME is empty or invalid format
    if ! [[ "$time" =~ ^([01]?[0-9]|2[0-3]):([0-5]?[0-9])$ ]]; then
        echo "Warning: Invalid checking time format '$time'. Defaulting to 00:00." >&2
        time="00:00"
    fi

    hour=$(echo "$time" | cut -d':' -f1)
    minute=$(echo "$time" | cut -d':' -f2)
    
    # Convert to integer to remove leading zeros for cron
    hour=${hour#0}
    minute=${minute#0}
    hour=${hour:-0} # Default to 0 if empty after removing 0
    minute=${minute:-0} # Default to 0 if empty after removing 0

    echo "$minute $hour * * *"
}

CRON_SCHEDULE=$(time_to_cron "$CHECKING_TIME")

cat > "$CRONTAB_FILE" <<EOF
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

$CRON_SCHEDULE   /usr/scripts/run_software_auto_upgrades.sh

EOF

if [ ! -f "$CRONTAB_FILE" ]; then
    echo "Error: Failed to create crontab file" >&2
    exit 1
fi

chmod 644 "$CRONTAB_FILE"

crontab -u "$CRONTAB_USER" "$CRONTAB_FILE"

if [ $? -ne 0 ]; then
    echo "Error setting cron job" >&2
    exit 1
fi

apt_daily_timer_enabled=$(systemctl is-enabled apt-daily.timer 2>/dev/null || echo "disabled")
apt_daily_upgrade_timer_enabled=$(systemctl is-enabled apt-daily-upgrade.timer 2>/dev/null || echo "disabled")

if [ "$apt_daily_timer_enabled" = "enabled" ]; then
    if ! systemctl disable --now apt-daily.timer > /dev/null 2>&1; then
        echo "Warning: Failed to disable apt-daily.timer" >&2
        # Continue execution, maybe timer doesnt exist or other issue
    fi
fi

if [ "$apt_daily_upgrade_timer_enabled" = "enabled" ]; then
    if ! systemctl disable --now apt-daily-upgrade.timer > /dev/null 2>&1; then
        echo "Warning: Failed to disable apt-daily-upgrade.timer" >&2
        # Continue execution
    fi
fi

renv set software_update_set_auto_upgrade_config_status success

exit 0