#!/usr/bin/env bash

set -o errexit
set -o nounset
set -o pipefail
if [[ "${TRACE-0}" == "1" ]]; then
    set -o xtrace
fi

# Colors
export ESC_SEQ="\x1b["
export COL_RESET=$ESC_SEQ"39;49;00m"
export COL_RED=$ESC_SEQ"31;01m"
export COL_GREEN=$ESC_SEQ"32;01m"
export COL_YELLOW=$ESC_SEQ"33;01m"
export COL_BLUE=$ESC_SEQ"34;01m"
export COL_MAGENTA=$ESC_SEQ"35;01m"
export COL_CYAN=$ESC_SEQ"36;01m"

function running() {
    echo -e "$COL_MAGENTA ⇒ $COL_RESET""$1"
}

function info() {
    echo -e "$COL_BLUE[info] $COL_RESET""$1"
}

function error() {
    echo -e "$COL_RED[error] $COL_RESET""$1"
}

OUTPUT_FOLDER="/tmp/DUMP"

if [[ "${1-}" =~ ^-*h(elp)?$ ]]; then
    echo 'Usage: hack/make/comp-objc-dump <dsc> <fw>

This script compares 2 `ipsw class-dump --headers` runs.

'
    exit
fi

clean() {
    running "Cleaning output folders..."
    declare -a paths_to_delete=(
        "${OUTPUT_FOLDER}"
        "${OUTPUT_FOLDER}"_PR
    )

    for path in "${paths_to_delete[@]}"; do
        info "Will delete ${path}"
    done

    read -p "Are you sure? " -n 1 -r
    echo # (optional) move to a new line
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        for path in "${paths_to_delete[@]}"; do
            info "Deleting ${path}"
            rm -rf "${path}"
        done
    fi
}

diff_clean() {
    find "${OUTPUT_FOLDER}" -name "*.h" | xargs sed -i '' '/   Generated.*/d'
    find "${OUTPUT_FOLDER}"_PR -name "*.h" | xargs sed -i '' '/   Generated.*/d'
}

run() {
    local dsc=$1
    local framework=$2
    ipsw class-dump --headers --deps "$dsc" "$framework" --output "$OUTPUT_FOLDER"
    go run ./cmd/ipsw/main.go class-dump --headers --deps "$dsc" "$framework" --output "$OUTPUT_FOLDER"_PR
}

compare() {
    COMPARE_FOLDERS=DIFF code "$OUTPUT_FOLDER" "$OUTPUT_FOLDER"_PR
}

check_ext() {
    local ext=$1
    local ext_list=$(code --list-extensions)
    if [[ ${ext_list} =~ (^|[[:space:]])${ext}($|[[:space:]]) ]]; then
        info "VSCode extension ${ext} installed."
    else
        error "VSCode extension ${ext} not installed. Run: 'code --install ${ext}'"
        exit 1
    fi
}

main() {
    echo "  🚀 Starting..."
    check_ext "moshfeu.compare-folders"
    clean
    run $1 $2
    diff_clean
    compare
    echo "  🎉 Done!"
}

main "$@"
