#!/bin/bash

log_dir="/var/log/software_update"
apt_update_log="${log_dir}/apt_update.log"

show_usage() {
    echo "Usage: $0 <command> [arguments]"
    echo "Commands:"
    echo "  update                      - Run apt-get update and log the result"
    echo "  get-update-log              - Get apt-get update log"
    echo "  get-repo-url <config>       - Get repository URL from config file"
    echo "  get-installed-rosp-apps     - Get list of installed ROS Pro packages"
    echo "  restore <file>              - Restore the original script"
    echo "  update-app-status           - Update installed ROS Pro packages status"
    exit 1
}

if [ $# -lt 1 ]; then
    show_usage
fi

if [ ! -d "$log_dir" ]; then
    mkdir -p "$log_dir"
fi

generate_random_filename() {
    local random_string=$(date +%s%N | md5sum | cut -c1-12)
    echo /tmp/sw_update_"$random_string"
}

get_repo_url_from_config() {
    local config_path=$1
    local cmd="sed -n '/^deb.*http/{ s/^deb \[.*\] \(http[^ ]*\).*/\1/; s/^deb \(http[^ ]*\).*/\1/; p; q; }' \"$config_path\""
    local url=$(eval $cmd)

    echo "${url// /}"
}

get_installed_rosp_apps() {
    new_apps=`dpkg-query -W -f='${Package}: ${App-Name-Web}\n' | grep -v ': $' | awk -F: '{print $1}'`
    #old_apps=`cat /app/dpkg/merge_app_list`
    apps=$(echo "$new_apps" | grep -v -E "^rosp-core$|^rosp$|^linux-image-" | sed 's/ *$//' | sort -u)

    echo "$apps"
}

case "$1" in
    "update")
        tmp_file=$(generate_random_filename)
        apt-get update > "$tmp_file" 2>&1
        return_code=$?

        echo $(date +%s) > $apt_update_log
        if [ $return_code -eq 0 ] && ! grep -q "^Err:" "$tmp_file"; then
            echo "success" >> $apt_update_log
        else
            echo "failed" >> $apt_update_log
        fi
        cat "$tmp_file" >> $apt_update_log
        rm -f "$tmp_file"

        usi set software_update.status_synced false
        usi sync software_update
        ;;
    "get-update-log")
        if [ -f "$apt_update_log" ]; then
            cat "$apt_update_log"
        else
            echo "Error: No update log found"
        fi
        ;;
    "get-repo-url")
        if [ $# -ne 2 ]; then
            echo "Error: get-repo-url requires config argument"
        else
            url=$(get_repo_url_from_config $2)
            if [ -z "$url" ]; then
                echo "Error: Failed to get repository URL from config file"
            else
                echo "$url"
            fi
        fi
        ;;
    "get-installed-rosp-apps")
        get_installed_rosp_apps
        ;;
    "restore")
        if [ $# -ne 2 ]; then
            echo "Error: restore requires file argument"
            exit 1
        else
            filename=$2
            if [ -f "$filename" ]; then
                converter -rf $filename
                if [ $? -eq 0 ]; then
                    echo "File $filename restored successful"
                    exit 0
                else
                    Error: "Failed to restore file $filename"
                    exit 1
                fi
            else
                echo "Error: File '$filename' not found"
                exit 1
            fi
        fi
        ;;
    "update-app-status")
        app_list="/app/dpkg/app_list"
        app_status_file="/app/dpkg/status"
        sys_app_list="/app/dpkg/sys_app_list"
        merge_app_list="/app/dpkg/merge_app_list"
        rm -f "$app_status_file"
        rm -f "$app_list"

        apps=$(get_installed_rosp_apps)

        for app in $apps; do
            echo "$app" >> "$app_list"
        done

        apps="$apps rosp-core"
        
        for app in $apps; do
            dpkg_info=$(dpkg -s "$app" 2>/dev/null)
            if [ $? -eq 0 ]; then
                package=$(echo "$dpkg_info" | grep "^Package:" | cut -d' ' -f2-)
                description=$(echo "$dpkg_info" | grep "^Description:" | cut -d' ' -f2-)
                version=$(echo "$dpkg_info" | grep "^Version:" | cut -d' ' -f2-)
                
                echo "Package: $package" >> "$app_status_file"
                echo "Description: $description" >> "$app_status_file"
                echo "Version: $version" >> "$app_status_file"
            fi
        done
        cat $sys_app_list $app_list 2>/dev/null | sed 's/ *$//' | sort -u > $merge_app_list
        ;;
    *)
        echo "Error: Unknown command '$1'"
        show_usage
        ;;
esac
