#!/bin/bash

ARCH=`uname -m`
if [[ $ARCH == "arm64" ]]; then
    PREFIX="/opt/homebrew/"
else
    PREFIX="/usr/local/"
fi

function set_permissions {
    echo "----------"
    echo "Disabling Quarantine for Casks ..."
    echo "----------"
    find $PREFIX/Caskroom -name *.app -exec bash -c "xattr -d com.apple.quarantine {} 2> /dev/null" \;
    find $PREFIX/Caskroom -type f -perm +111 -exec bash -c "xattr -d com.apple.quarantine {} 2> /dev/null" \; 
    find /Applications/ -name *.app -exec bash -c 'xattr -d com.apple.quarantine "{}" 2> /dev/null' \;
    find /Applications/ -type f -perm +111 -exec bash -c 'xattr -d com.apple.quarantine "{}" 2> /dev/null' \;
}

function software_update {
    echo "----------"
    echo "Running software update"
    echo "----------"
    softwareupdate --all --install --force
}

function update_brew {
    echo "----------"
    echo "Updating brew software"
    echo "----------"
    brew update
    brew upgrade
    echo "----------"
    echo "Updating casks"
    echo "----------"
    brew upgrade --cask --greedy --verbose
}

function cleanup {
    echo "----------"
    echo "Running cleanup"
    echo "----------"
    brew cleanup -s
}

function diagnostics {
    echo "----------"
    echo "Running diagnostics"
    echo "----------"
    brew doctor
    brew missing
}
if [[ $* == *--help* ]]; then
    echo "Usage: $0 [option]"
    echo "Default options: --brew-update --cleanup --diagnostics"
    echo -e "Options:\n\t--brew-update\n\t--cleanup\n\t--diagnostics\n\t--permission-fix\n\t--system-update"
fi

if [[ -z $* ]]; then
    set -- "$*" "--brew-update --cleanup --diagnostics"
fi

if [[ $* == *--system-update* ]]; then
    software_update
fi
if [[ $* == *--brew-update* ]]; then
    update_brew
fi
if [[ $* == *--cleanup* ]]; then
    cleanup
fi
if [[ $* == *--diagnostics* ]]; then
    diagnostics
fi
if [[ $* == *--permission-fix* ]]; then
    set_permissions
fi
