#!/bin/bash
set -e

# --- 0. Pre-requirements ---
echo "Installing Git and dependencies..."
sudo apt update
sudo apt install -y git curl wget dconf-editor x11-utils \
    sassc libsass1 unattended-upgrades htop apt-listchanges

# --- 0.1 Configure Unattended-Upgrades (The Clean Bash Way) ---
echo "Dynamically mapping APT origins..."

# 1. Extract active origins and archives, then format them for the config
# This looks at your current 'apt-cache policy', finds the o= and a= lines,
# and turns them into "Origin:Archive";
DYNAMIC_ORIGINS=$(apt-cache policy | grep 'o=' | grep 'a=' | sed -re 's/.*o=([^,]+),a=([^, ]+).*/    "\1:\2";/' | sort -u)

# 2. Write the config using the discovered origins
sudo tee /etc/apt/apt.conf.d/50unattended-upgrades <<EOF
Unattended-Upgrade::Allowed-Origins {
$DYNAMIC_ORIGINS
};

Unattended-Upgrade::Package-Blacklist { };
Unattended-Upgrade::AutoFixInterruptedDpkg "true";
Unattended-Upgrade::MinimalSteps "true";
Unattended-Upgrade::InstallOnShutdown "false";
Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";
Unattended-Upgrade::Remove-New-Unused-Dependencies "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-WithUsers "true";
Unattended-Upgrade::Automatic-Reboot-Time "04:00";
EOF

# 3. Enable the daily trigger
sudo tee /etc/apt/apt.conf.d/20auto-upgrades <<EOF
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Unattended-Upgrade "1";
EOF

# Test command: sudo unattended-upgrade --dry-run --debug
echo "Done! Detected Origins:"
echo "$DYNAMIC_ORIGINS"

TEMP_DIR=$(mktemp -d)
echo "Creating temporary workspace at $TEMP_DIR..."
cd "$TEMP_DIR"

# --- 1. Install SF Pro Fonts ---
echo "Installing San Francisco Pro Fonts..."
git clone --depth 1 https://github.com/sahibjotsaggu/San-Francisco-Pro-Fonts.git
sudo mkdir -p /usr/local/share/fonts/apple-san-francisco
find San-Francisco-Pro-Fonts -name "*.[o|t]tf" -exec sudo cp {} /usr/local/share/fonts/apple-san-francisco/ \;

# --- 2. Install SF Mono Fonts ---
echo "Installing SF Mono Fonts..."
git clone --depth 1 https://github.com/supercomputra/SF-Mono-Font.git
find SF-Mono-Font -name "*.otf" -exec sudo cp {} /usr/local/share/fonts/apple-san-francisco/ \;

# Fix Font Permissions & Update Cache
sudo chmod 755 /usr/local/share/fonts/apple-san-francisco
sudo chmod 644 /usr/local/share/fonts/apple-san-francisco/*
sudo fc-cache -f

# --- 3. Install Boston Icons ---
echo "Installing Boston Icons..."
git clone --depth 1 https://github.com/thecheis/Boston-Icons
sudo mkdir -p /usr/share/icons/Boston
sudo cp -r Boston-Icons/* /usr/share/icons/Boston/
sudo chown -R root:root /usr/share/icons/Boston
sudo find /usr/share/icons/Boston -type d -exec chmod 755 {} +
sudo find /usr/share/icons/Boston -type f -exec chmod 644 {} +

# --- 4. Install Orchis Theme ---
echo "Installing Orchis Theme..."
git clone --depth 1 https://github.com/vinceliuice/Orchis-theme
cd Orchis-theme
sudo ./install.sh -d /usr/share/themes -c dark -s compact --round 10 --tweaks compact
cd ..

# --- 5. Install Topgrade ---
echo "Fetching latest Topgrade..."
TOPGRADE_VER=$(curl -s "https://api.github.com/repos/topgrade-rs/topgrade/releases/latest" | grep -Po '"tag_name": "v\K[^"]*')
DEB_URL="https://github.com/topgrade-rs/topgrade/releases/download/v${TOPGRADE_VER}/topgrade_${TOPGRADE_VER}-1_amd64.deb"
curl -LO "$DEB_URL"
sudo apt install ./*.deb -y

# --- 6. Install 'am' (AppImage Manager) ---
echo "Installing 'am' package manager..."
curl -sSL https://raw.githubusercontent.com/ivan-hc/AM/main/INSTALL | sudo bash

# --- 7. Apply XFCE Appearance & Window Settings ---
echo "Applying XFCE Theme, Font, and WM settings..."
xfconf-query -c xsettings -p /Net/ThemeName -s "Orchis-Dark-Compact"
xfconf-query -c xsettings -p /Net/IconThemeName -s "Boston"
xfconf-query -c xsettings -p /Gtk/FontName -s "SF Pro Display 10"
xfconf-query -c xsettings -p /Gtk/MonospaceFontName -s "SF Mono 10"
xfconf-query -c xfwm4 -p /general/theme -s "Orchis-Dark-Compact"
xfconf-query -c xfwm4 -p /general/title_font -s "SF Pro Display Bold 10"
xfconf-query -c xfwm4 -p /general/title_alignment -s "center"

# --- 8. The Top Panel Fix & Logo Customization ---
echo "Configuring Top Panel and Menu Icon..."
xfce4-panel -q || killall xfce4-panel || true
killall xfconfd || true
sleep 1

# Snap to top absolute edge
xfconf-query -c xfce4-panel -p /panels/panel-1/position -n -t string -s "p=6;x=0;y=0"
xfconf-query -c xfce4-panel -p /panels/panel-1/size -n -t uint -s 30
xfconf-query -c xfce4-panel -p /panels/panel-1/length -n -t uint -s 100
xfconf-query -c xfce4-panel -p /panels/panel-1/position-locked -n -t bool -s true

# Apply the Boston Start Icon to Whisker Menu (assuming plugin-1)
xfconf-query -c xfce4-panel -p /plugins/plugin-1/button-icon -n -t string -s "/usr/share/icons/Boston/128/places/start-here.svg"
xfconf-query -c xfce4-panel -p /plugins/plugin-1/show-button-title -n -t bool -s false
xfconf-query -c xfce4-panel -p /plugins/plugin-1/menu-opacity -n -t uint -s 0

# The Fixes for plank and firefox
xfconf-query -c xfwm4 -p /general/show_dock_shadow -n -t bool -s false
xfconf-query -c xfwm4 -p /general/borderless_maximize -n -t bool -s false

# --- 9. Install and Configure Plank ---
echo "Cleaning Plank and setting custom launchers..."
sudo apt install plank -y

mkdir -p ~/.config/autostart
cat <<EOF > ~/.config/autostart/plank.desktop
[Desktop Entry]
Type=Application
Exec=plank
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name=Plank
EOF
(plank &)
sleep 2
gsettings set net.launchpad.plank.dock.settings:/net/launchpad/plank/docks/dock1/ theme 'Gtk+'
gsettings set net.launchpad.plank.dock.settings:/net/launchpad/plank/docks/dock1/ zoom-enabled true
gsettings set net.launchpad.plank.dock.settings:/net/launchpad/plank/docks/dock1/ zoom-percent 150
gsettings set net.launchpad.plank.dock.settings:/net/launchpad/plank/docks/dock1/ icon-size 48
gsettings set net.launchpad.plank.dock.settings:/net/launchpad/plank/docks/dock1/ hide-mode 'window-dodge'

# --- 10. Final Cleanup ---
echo "Cleaning up..."
cd /tmp
rm -rf "$TEMP_DIR"
(xfce4-panel &)

echo "------------------------------------------------"
echo "COMPLETE: Your Mac-Mint Build is Ready!"
echo "------------------------------------------------"