#!/bin/bash

# Script to configure podman for the local environment
#
# ./podman_setup

set -euo pipefail

if ! command -v podman &>/dev/null; then
    echo "Error: podman is not installed"
    exit 1
fi

case "$(uname -s)" in
    Darwin*) memory=12288 ;;
    Linux*) memory=8192 ;;
    *)
        echo "Unsupported platform"
        exit 1
        ;;
esac

if [[ "$(uname -s)" == Darwin* ]]; then
    helper_plist="/Library/LaunchDaemons/com.github.containers.podman.helper-$(whoami).plist"
    if [[ ! -f "$helper_plist" ]]; then
        echo "Installing podman-mac-helper (requires sudo)..."
        sudo podman-mac-helper install
    fi
fi

if ! podman machine inspect &>/dev/null; then
    echo "Initializing podman machine with 4 CPUs and $((memory / 1024))GB RAM..."
    podman machine init --rootful --cpus 4 --memory "$memory"
fi

if [[ "$(uname -s)" == Darwin* ]]; then
    rosetta=$(podman machine inspect --format '{{.Rosetta}}')
    if [[ "$rosetta" != "true" ]]; then
        echo "Warning: Rosetta translation is not enabled on this podman machine."
    fi
fi

state=$(podman machine inspect --format '{{.State}}')
case "$state" in
    running)
        echo "Podman machine is already running."
        ;;
    stopped)
        echo "Starting podman machine..."
        podman machine start
        ;;
    *)
        echo "Error: podman machine is in unexpected state: $state"
        exit 1
        ;;
esac

case "$(uname -s)" in
    Darwin*) resolved_ip=$(dscacheutil -q host -a name host.docker.internal 2>/dev/null | awk '/^ip_address:/{print $2; exit}') ;;
    *) resolved_ip=$(getent hosts host.docker.internal 2>/dev/null | awk '{print $1}') ;;
esac
if [[ -z "$resolved_ip" ]] || ! echo "$resolved_ip" | grep -qE '^(127\.|::1$)'; then
    echo "Adding host.docker.internal to /etc/hosts (requires sudo)..."
    echo "127.0.0.1 host.docker.internal" | sudo tee -a /etc/hosts >/dev/null
fi

if [[ ! -e /usr/local/bin/docker ]]; then
    echo "Creating docker symlink to avoid issues with projects that do not inherit aliases (requires sudo)..."
    sudo ln -s "$(command -v podman)" /usr/local/bin/docker
fi
