#!/bin/bash

greeting() {
    echo "
------------------------------------- Info -------------------------------------
Dieses Script checkt, ob einige Settings gesetzt sind die für die Sicherheit
von MacBooks wichtig sind.
Am Ende des Scripts wird eine Log-Datei in eurem Download Ordner erstellt,
die alle Ergebnisse beinhaltet.

Bitte schickt diese Log-Datei per mail an role-ops@protofy.com.
--------------------------------------------------------------------------------
    "
}

check_root() {
    # Check if script is run as root
    if [[ $EUID -eq 0 ]]; then
        echo "Dieses Script sollte nicht als root ausgeführt werden. Bitte nochmal ausführen als normaler User." 1>&2
        exit 1
    fi
}

check_filevault() {
    # Check if FileVault is enabled
    if [[ $(fdesetup status) == "FileVault is On." ]]; then
        filevault_status="FileVault is enabled"
    else
        filevault_status="FileVault is not enabled"
    fi
    echo $filevault_status
}

check_findmymac() {
    fmmToken=$(/usr/sbin/nvram -x -p | /usr/bin/grep fmm-mobileme-token-FMM)
    if [[ -z $fmmToken ]]; then
        findmymac_status="Find My Mac is not enabled"
    else
        findmymac_status="Find My Mac is enabled"
    fi
    echo $findmymac_status
}

check_osversion() {
    os_string=$(system_profiler SPSoftwareDataType | grep "System Version")
    os_version=$(echo $os_string | cut -d ":" -f 2)
    echo $os_version
}

check_autologin() {
    if [[ -f /etc/kcpassword ]]; then
        autologin_status="Autologin might be enabled"
    else
        autologin_status="Autologin is not enabled"
    fi
    echo $autologin_status
}

check_timemachine() {
    backup_volume=$(tmutil destinationinfo | grep "URL" | awk '{print $3}')

    if [[ $backup_volume == "afp"* ]]; then
        timemachine_status="Backing up to ${backup_volume}"
    else
        timemachine_status="Time Machine is not enabled"
    fi
    echo $timemachine_status
}

# Setup logfile
USERNAME=$(whoami)
LOGFILE="/Users/$USERNAME/Downloads/security_check.log"
if [[ ! -f $LOGFILE ]]; then
    touch $LOGFILE
fi

#check_root
greeting
HOSTNAME=$(hostname)
OSVERSION=$(check_osversion)
SERIAL_NUMBER=$(system_profiler SPHardwareDataType | grep "Serial Number" | cut -d ":" -f 2 | tr -d " ")
MODEL_IDENTIFIER=$(system_profiler SPHardwareDataType | grep "Model Identifier" | cut -d ":" -f 2 | tr -d " ")
MODEL_NUMBER=$(system_profiler SPHardwareDataType | grep "Model Number" | cut -d ":" -f 2 | tr -d " ")
FILEVAULT=$(check_filevault)
TIMEMACHINE=$(check_timemachine)
FINDMYMAC=$(check_findmymac)
AUTOLOGIN=$(check_autologin)
# Write results to logfile
echo "$(date), $USERNAME, $HOSTNAME, $OSVERSION, $SERIAL_NUMBER, \"$MODEL_IDENTIFIER\", $MODEL_NUMBER, $FILEVAULT, $TIMEMACHINE, $FINDMYMAC, $AUTOLOGIN" >$LOGFILE
