#!/bin/bash
#
## Init macOS env

# Update PATH
for p in /usr/local/{,opt/{e2fsprogs,ruby,util-linux}/}{bin,sbin}; do
  PATH="${p}:${PATH}"
done

# Create and mount RAM_Disk
if ! [[ -d /Volumes/RAM_Disk ]]; then
  echo "Creating RAM Disk..."
  RAM_DEV="$(hdiutil attach -nomount ram://524288)"
  diskutil quiet erasevolume HFS+ RAM_Disk ${RAM_DEV}
  diskutil quiet unmount ${RAM_DEV}
  mkdir /Volumes/RAM_Disk
  mount -t hfs -o owners ${RAM_DEV} /Volumes/RAM_Disk
fi
cd /Volumes/RAM_Disk

# Connect to WiFi?
if ! [[ -e /Volumes/RAM_Disk/.wifi ]]; then
  WIFI_NET="$(fgrep ':::' /.known_networks | head -1)"
  if ! ifconfig | grep -Eq '(((10|172)\.\d+|192.168)\.\d+\.\d+)' 2>/dev/null; then
    echo "Connecting to WiFi..."
    NET_DEV="$(/usr/sbin/networksetup \
      -listallhardwareports \
      | tr -d '\n' \
      | grep -Eo 'Wi-Fi.*?Device.*?(en\d+)' \
      | grep -Eo 'en(\d+)')"
    networksetup -setairportnetwork "${NET_DEV}" "${WIFI_NET%%:::*}" "${WIFI_NET##*:::}"
    touch /Volumes/RAM_Disk/.wifi
    sleep 8s
  fi
fi

# Dropbear (SSH)
if ! [[ -d /Volumes/RAM_Disk/.ssh ]]; then
  echo "Starting SSH server..."
  mkdir /Volumes/RAM_Disk/.ssh
  cp /.authorized_keys /Volumes/RAM_Disk/.ssh/authorized_keys
  chown -R 0:0 /Volumes/RAM_Disk/.ssh
  chmod 700 /Volumes/RAM_Disk/.ssh
  chmod 600 /Volumes/RAM_Disk/.ssh/authorized_keys
  dropbear -s
fi

# Stay awake
echo "Getting caffeinated..."
caffeinate -id &

# Set time
if ! [[ -e /Volumes/RAM_Disk/.time_set ]]; then
  echo "Updating clock..."
  if ! sntp -Ss us.pool.ntp.org >/dev/null 2>&1; then
    # Assuming we're running under an older version of macOS
    sntp -s us.pool.ntp.org >/dev/null 2>&1
  fi
  touch /Volumes/RAM_Disk/.time_set
fi

# Run cmd
"$1"
