#!/bin/bash

## unquarantine.command
# Basic script for fixing apps that get blocked by Gatekeeper on Macs, especially Apple Silicon Macs.
# "This app my harm your mac" or other such messages.
# Make the script executable (chmod +x) then double-click it, and follow the directions
#

echo "Drag an app (or other file) from Finder into this window, then press Enter."
echo "Optionally type flags immediately before it, no space needed: c = clear all extended attrs, s = force re-sign (e.g. 'cs' then drag)."
echo "The dropped path must be absolute (starting with /), as Finder drag-and-drop provides by default."
echo "Press Ctrl+C to quit."

while true; do
    echo
    read -r -p "> " line
    [ -z "$line" ] && continue

    if [[ "$line" =~ ^[[:space:]]*(c|s|cs|sc)?[[:space:]]*(/.*)$ ]]; then
        flags="${BASH_REMATCH[1]}"
        path_part="${BASH_REMATCH[2]}"
    else
        echo "Couldn't parse that — the dropped path must be absolute (start with /)."
        continue
    fi

    # Terminal inserts dropped paths as backslash-escaped shell words.
    eval "files=($path_part)"

    any_ok=false
    for f in "${files[@]}"; do
        if [ ! -e "$f" ]; then
            echo "Not found: $f"
            continue
        fi

        if [[ "$flags" == *c* ]]; then
            echo "Clearing all extended attributes from: $f"
            xattr -cr "$f"
        else
            echo "Removing quarantine attribute from: $f"
            xattr -d com.apple.quarantine -r "$f"
        fi

        if [[ "$flags" == *s* ]]; then
            echo "Force re-signing: $f"
            codesign --force --deep --sign - "$f"
        elif codesign -dv "$f" &>/dev/null; then
            echo "Already signed."
        else
            echo "Not signed — ad-hoc signing: $f"
            codesign --force --deep --sign - "$f"
        fi

        any_ok=true
    done

    $any_ok && echo "Done."
done
