#!/bin/bash

# Status.app - lightweight, non-root companion to Hunter.app.
#
# Deployed to /Applications by Hunter.app during install (copied from
# Hunter's own Resources folder, same pattern as SafeAccessSolution8.crt),
# so it persists and remains available independently of Hunter itself.
#
# This script deliberately runs with NO elevated privileges (Platypus
# "root privileges" unchecked). It re-derives this Mac's serial number,
# does a lightweight check-in with the server, and - if the current
# console user is NOT an admin (i.e. Hunter has already locked this
# account down) AND the server has authorized removal (installState =
# disable_proxy) - lets the user know. It cannot perform the removal
# itself; that's the point of it having no elevated privileges.

DEBUG_MODE=false  # Set to true for troubleshooting only

DEBUG_SHOW_JSON=false  # Do not let customers see Protection password.

TEST_MODE=false

if $TEST_MODE; then
    REG_URL="http://192.168.20.6:8080/mac_reg.php"
else
    REG_URL="https://www.gamblock.com/php/macos/mac_reg/3/mac_reg.php"
fi

# Logs go to the same location hunter.sh uses - outside TCC's jurisdiction
# so no permission prompt/failure is possible.
LOG_DIR="$HOME/Protect"
mkdir -p "$LOG_DIR" 2>/dev/null

if $DEBUG_MODE; then
    LOG="$LOG_DIR/status_log.txt"
else
    LOG="/dev/null"
fi


log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG"
}

log "===== Status run started ====="

# Re-derive the serial the same way hunter.sh does.
SERIAL=$(ioreg -c IOPlatformExpertDevice -d 2 | awk -F'"' '/IOPlatformSerialNumber/{print $4}')
log "Serial: $SERIAL"


# Lightweight check-in: serial only, no email prompt, no cert/proxy work -
# just enough to get installState back. mac_reg.php only requires serial;
# email is optional and left blank here.
RESPONSE=$(curl -s -m 10 -X POST "$REG_URL" --data-urlencode "serial=$SERIAL")

if [ "$DEBUG_SHOW_JSON" = "true" ]; then

    log "Response: $RESPONSE"

fi


INSTALL_STATE=$(echo "$RESPONSE" | grep -o '"installState":"[^"]*"' | sed 's/"installState":"//;s/"$//')
log "Install State: $INSTALL_STATE"

PROTECTION_ADMIN_PASS=$(echo "$RESPONSE" | grep -o '"protectionAdminPass":"[^"]*"' | sed 's/"protectionAdminPass":"//;s/"$//')

# Same admin check as hunter.sh's top-level gate.
CURRENT_USER=$(stat -f%Su /dev/console)
if dscl . -read /Groups/admin GroupMembership 2>/dev/null | grep -q "$CURRENT_USER"; then
    CURRENT_USER_IS_ADMIN=true
else
    CURRENT_USER_IS_ADMIN=false
fi
log "Current user: $CURRENT_USER, is admin: $CURRENT_USER_IS_ADMIN"

# Escaped once, unconditionally, so it's safe to use in any dialog below -
# not just the branch that originally computed it.
ESCAPED_CURRENT_USER=$(printf '%s' "$CURRENT_USER" | sed 's/\\/\\\\/g; s/"/\\"/g')

if [ "$INSTALL_STATE" = "disable_proxy" ]; then

    if [ "$CURRENT_USER_IS_ADMIN" = false ]; then

        # Double-quoted (not single-quoted) so $CURRENT_USER and
        # $PROTECTION_ADMIN_PASS actually expand - and escaped so either
        # value can't break out of the AppleScript string if it happens to
        # contain a quote or backslash.
        ESCAPED_PROTECTION_ADMIN_PASS=$(printf '%s' "$PROTECTION_ADMIN_PASS" | sed 's/\\/\\\\/g; s/"/\\"/g')
        log "Showing: removal-authorised, non-admin dialog"
        osascript -e "display dialog \"Removal has been authorised.\n\nTo remove:\n\n1)\n\nLog in as the Protection admin account, with the password:\n\n    $ESCAPED_PROTECTION_ADMIN_PASS\n\n2)\n\nMake this account ($ESCAPED_CURRENT_USER) administrator.\n\n3)\n\nLog back into this account ($ESCAPED_CURRENT_USER) and open Hunter to complete removal.\" buttons {\"OK\"} default button \"OK\"" 2>>"$LOG"
        if [ $? -ne 0 ]; then
            log "ERROR: osascript failed to display the removal-authorised dialog"
        fi
    else

        log "Showing: removal-authorised, admin dialog"
        osascript -e "display dialog \"Open Hunter to complete removal.\" buttons {\"OK\"} default button \"OK\"" 2>>"$LOG"
        if [ $? -ne 0 ]; then
            log "ERROR: osascript failed to display the open-Hunter dialog"
        fi

    fi

else

    if [ "$CURRENT_USER_IS_ADMIN" = false ]; then

        log "Showing: still-protected, non-admin dialog"
        osascript -e "display dialog \"The device is still within a protection period.\n\nThe Hunter app cannot be used while this account ($ESCAPED_CURRENT_USER) is not administrator.\" buttons {\"OK\"} default button \"OK\"" 2>>"$LOG"
        if [ $? -ne 0 ]; then
            log "ERROR: osascript failed to display the still-protected non-admin dialog"
        fi
    else

        log "Showing: still-protected, admin dialog"
        osascript -e "display dialog \"The device is still within a protection period.\" buttons {\"OK\"} default button \"OK\"" 2>>"$LOG"
        if [ $? -ne 0 ]; then
            log "ERROR: osascript failed to display the still-protected admin dialog"
        fi

    fi

fi

log "===== Status run finished ====="

if [ "$DEBUG_MODE" = "true" ]; then
    open "$LOG_DIR"
fi

exit 0

