#!/bin/bash

# /var/lib/waydroid
# ~/.local/share/waydroid/data
# user=$(logname)
DATA_DIR=$(realpath "/home/$(logname)/.local/share/waydroid/data")
VAR_DIR=$(realpath "/var/lib/waydroid")
OVERLAY_DIR="$VAR_DIR/overlay"
OVERLAY_RW_DIR="$VAR_DIR/overlay_rw"

function run_waydroid_upgrade {
    local o_option=$1
    if [ "$o_option" == "-o" ]; then
        waydroid upgrade -o
    else
        waydroid upgrade
    fi
}

# $1: source
# $2: /var/lib/waydroid/$2
function copy_to_var() {
    dest_path=$(realpath -m "$VAR_DIR/$2")
    if [[ "$dest_path" == "$VAR_DIR"/* ]]; then
        # copy -rf "$1" "$dest_path"
        if [ ! -e "$dest_path" ]; then
            if [[ "${2: -1}" == "/" ]]; then
                mkdir -p "$dest_path"
                cp -rf "$1" "$dest_path/"
            else
                mkdir -p $(dirname "$dest_path")
                cp -rf "$1" "$dest_path"
            fi
        else
            cp -rf "$1" "$dest_path"
        fi
    else
        echo "Error: $dest_path is outside of $VAR_DIR" >&2
        exit 1
    fi
    
}

function rm_var() {
    dest_path=$(realpath -m "$VAR_DIR/$1")
    if [[ "$dest_path" == "$VAR_DIR"/* ]]; then
        rm -rf "$dest_path"
    else
        echo "Error: $dest_path is outside of $VAR_DIR" >&2
        exit 1
    fi
    
}

function rm_overlay() {
    local files=("$@")
    for file in "${files[@]}"; do
        rm_var "overlay/$file"
    done
}

function rm_overlay_rw() {
    local files=("$@")
    for file in "${files[@]}"; do
        rm_var "overlay_rw/$file"
    done
}


# $1 startdir
# $2 name
# $3 version
function call_package() {
    startdir=$1
    name=$2
    version=$3
    echo $name $version
    srcdir="$startdir/src"
    pkgdir="$startdir/pkg"
    rm -rf $srcdir && mkdir -p $srcdir
    rm -rf $pkgdir && mkdir -p $pkgdir

    # 尝试使用 fakeroot，如果失败则使用 fakeroot-sysv
    if ! fakeroot bash -c "set -e;CARCH=$CARCH startdir=$startdir srcdir=$srcdir pkgdir=$pkgdir;cd $startdir;source $startdir/EXTENSION && package; tar -czpf \"${name}-${version}.tar.gz\" -C pkg ."; then
        echo "fakeroot failed, checking for fakeroot-sysv..."
        if command -v fakeroot-sysv >/dev/null 2>&1; then
            echo "Using fakeroot-sysv as fallback..."
            rm -rf $srcdir && mkdir -p $srcdir
            rm -rf $pkgdir && mkdir -p $pkgdir
            fakeroot-sysv bash -c "set -e;CARCH=$CARCH startdir=$startdir srcdir=$srcdir pkgdir=$pkgdir;cd $startdir;source $startdir/EXTENSION && package; tar -czpf \"${name}-${version}.tar.gz\" -C pkg ."
        else
            echo "Error: fakeroot-sysv not found, cannot proceed" >&2
            exit 1
        fi
    fi
}
function install_tar_gz() {
    tar -xzpf "$1" -C "$OVERLAY_DIR"
}

function cp_to_data() {
    eval "src_path=\"$1\""
    dest_path=$(realpath -m "$DATA_DIR/$2")
    if [[ "$dest_path" == "$DATA_DIR"/* ]]; then
        # copy -rf "$1" "$dest_path"
        if [ ! -e "$dest_path" ]; then
            if [[ "${2: -1}" == "/" ]]; then
                mkdir -p "$dest_path"
                cp -rf "$src_path" "$dest_path/"
            else
                mkdir -p $(dirname "$dest_path")
                cp -rf "$src_path" "$dest_path"
            fi
        else
            cp -rf "$src_path" "$dest_path"
        fi
    else
        echo "Error: $dest_path is outside of $DATA_DIR" >&2
        exit 1
    fi
    
}

function rm_apk() {
    local apks=("$@")
    for apk in "${apks[@]}"; do
        waydroid shell -- sh -c "pm uninstall $apk"
    done
}

function rm_data(){
    local patterns=("$@")
    for pattern in "${patterns[@]}"; do
        # Change to DATA_DIR to perform glob expansion
        pushd "$DATA_DIR" > /dev/null 2>&1

        # Expand the pattern using shell globbing
        local expanded_files=()
        shopt -s nullglob  # Don't include pattern itself if no matches
        expanded_files=($pattern)
        shopt -u nullglob

        popd > /dev/null 2>&1

        # If no files matched the pattern, show a warning
        if [ ${#expanded_files[@]} -eq 0 ]; then
            echo "Warning: No files matched pattern '$pattern' in $DATA_DIR" >&2
            continue
        fi

        # Process each expanded file
        for file in "${expanded_files[@]}"; do
            dest_path=$(realpath -m "$DATA_DIR/$file")
            if [[ "$dest_path" == "$DATA_DIR"/* ]]; then
                echo "Removing: $dest_path"
                rm -rf "$dest_path"
            else
                echo "Error: $dest_path is outside of $DATA_DIR" >&2
                exit 1
            fi
        done
    done
}

action=$1
shift

case "$action" in
    upgrade)
        o_option=""
        while getopts ":o" opt; do
            case $opt in
                o) o_option="-o" ;;
            esac
        done
        run_waydroid_upgrade "$o_option"
    ;;
    restart_container)
        waydroid container restart
    ;;
    # copy)
    #     if [ $# -lt 2 ]; then
    #         echo "Usage: $0 copy <source> <destination> [--contents-only]"
    #         exit 1
    #     fi
    #     source=$1
    #     destination=$2
    #     contents_only="false"
    #     if [ "$3" == "--contents-only" ]; then
    #         contents_only="true"
    #     fi
    #     copy "$source" "$destination" "$contents_only"
    # ;;
    rm)
        if [ $# -lt 1 ]; then
            echo "Usage: $0 rm <files>"
            exit 1
        fi
        remove_files_and_directories "$@"
    ;;
    rm_overlay)
        if [ $# -lt 1 ]; then
            echo "Usage: $0 rm_overlay <files>"
            exit 1
        fi
        rm_overlay "$@"
    ;;
    rm_overlay_rw)
        if [ $# -lt 1 ]; then
            echo "Usage: $0 rm_overlay_rw <files>"
            exit 1
        fi
        rm_overlay_rw "$@"
    ;;
    rm_apk)
        if [ $# -lt 1 ]; then
            echo "Usage: $0 rm_apk <apks>"
            exit 1
        fi
        rm_apk "$@"
    ;;
    rm_data)
        if [ $# -lt 1 ]; then
            echo "Usage: $0 rm_data <files>"
            exit 1
        fi
        rm_data "$@"
    ;;
    install)
        if [ $# -lt 1 ]; then
            echo "Usage: $0 install <package>"
            exit 1
        fi
        install_tar_gz "$1"
    ;;
    call_package)
        if [ $# -lt 1 ]; then
            echo "Usage: $0 call_package <startdir>"
            exit 1
        fi
        call_package "$1" "$2" "$3"
    ;;
    copy_to_var)
        if [ $# -lt 2 ]; then
            echo "Usage: $0 copy_to_var <source> <destination>"
            exit 1
        fi
        source=$1
        destination=$2
        copy_to_var "$source" "$destination"
    ;;
    cp_to_data)
        if [ $# -lt 2 ]; then
            echo "Usage: $0 cp_to_data <source> <destination>"
            exit 1
        fi
        source=$1
        destination=$2
        cp_to_data "$source" "$destination"
    ;;
    clear_package_cache)
        # Change to the system directory to handle wildcards properly
        cd "$DATA_DIR/system" || exit 1

        # Define the specific files and directories to clear
        cache_items=("packages.list" "packages.xml" "package-watchdog.xml" "package_cache")
        found_items=()

        # Check which items exist
        for item in "${cache_items[@]}"; do
            if [ -e "$item" ]; then
                found_items+=("$item")
            fi
        done

        if [ ${#found_items[@]} -gt 0 ]; then
            # Create backup with timestamp in parent directory to avoid deletion
            backup_file="../package_cache_backup_$(date +%s).tar.gz"
            echo "Creating backup: $backup_file"
            tar -czpf "$backup_file" "${found_items[@]}"

            # Remove the actual package cache files and directories
            echo "Removing package cache files..."
            rm -rf "${found_items[@]}"
            echo "Package cache cleared successfully"
        else
            echo "No package cache files found to clear"
        fi
    ;;
    *)
        echo "Unknown action: $action"
        echo "Usage: $0 <action> [options]"
        exit 1
    ;;
esac