#!/bin/bash

# Ensure script is run as root
if [ "$EUID" -ne 0 ]; then
  echo "❌ Please run this script with sudo or as root."
  exit 1
fi

CONFIG_FILE="/etc/telegram.conf"
SCRIPT_PATH="/usr/local/bin/telegram-shutdown-notify.sh"
SERVICE_PATH="/etc/systemd/system/telegram-shutdown-notify.service"

echo "=========================================="
echo " Telegram Shutdown/Reboot Alert Installer"
echo "=========================================="
echo ""

# Abort check: File must exist
if [ ! -f "$CONFIG_FILE" ]; then
  echo "❌ Error: Configuration file $CONFIG_FILE does not exist. Aborting."
  exit 1
fi

# Load config
source "$CONFIG_FILE" 2>/dev/null

# Abort check: Variables must not be empty
if [ -z "$TELEGRAM_BOT_TOKEN" ] || [ -z "$TELEGRAM_CHAT_ID" ]; then
  echo "❌ Error: $CONFIG_FILE found, but TELEGRAM_BOT_TOKEN or TELEGRAM_CHAT_ID is missing or empty. Aborting."
  exit 1
fi

echo "✅ Valid configuration confirmed at $CONFIG_FILE"

echo "⚙️ Creating shutdown script at $SCRIPT_PATH..."

# Write the main shutdown notification script
cat << 'EOF' > "$SCRIPT_PATH"
#!/bin/bash

CONFIG_FILE="/etc/telegram.conf"

# Verify config exists and load it
if [ ! -f "$CONFIG_FILE" ]; then
  echo "Error: Configuration file $CONFIG_FILE not found." >&2
  exit 1
fi

source "$CONFIG_FILE"

if [ -z "$TELEGRAM_BOT_TOKEN" ] || [ -z "$TELEGRAM_CHAT_ID" ]; then
  echo "Error: TELEGRAM_BOT_TOKEN or TELEGRAM_CHAT_ID is empty in $CONFIG_FILE." >&2
  exit 1
fi

# Detect whether this is a Reboot or a Poweroff/Shutdown
SYSTEMD_ACTION=$(systemctl list-jobs 2>/dev/null)

if echo "$SYSTEMD_ACTION" | grep -qE "reboot.target.*start"; then
  EVENT_TYPE="Rebooting 🔄"
elif echo "$SYSTEMD_ACTION" | grep -qE "poweroff.target.*start|halt.target.*start"; then
  EVENT_TYPE="Shutting Down 🛑"
else
  # Default fallback if run manually or during generic stop
  EVENT_TYPE="Stopping / Shutting Down 🛑"
fi

# Get current date, time, and server uptime
DATE_TIME=$(date "+%Y-%m-%d %H:%M:%S %Z")
HOSTNAME=$(hostname)
UPTIME_INFO=$(uptime -p 2>/dev/null || echo "N/A")

# Build message payload
MESSAGE="🛑 *Server Event: $EVENT_TYPE*

🖥 *Host:* \`$HOSTNAME\`
📅 *Date & Time:* \`$DATE_TIME\`
⏱ *Uptime before event:* \`$UPTIME_INFO\`"

# Send via Telegram API
curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
     -d "chat_id=${TELEGRAM_CHAT_ID}" \
     -d "parse_mode=Markdown" \
     --data-urlencode "text=${MESSAGE}" > /dev/null
EOF

# Set secure permissions on script
chmod 700 "$SCRIPT_PATH"

echo "⚙️ Creating systemd service at $SERVICE_PATH..."

# Systemd unit configured to fire ONLY when stopping before network shuts down
cat << EOF > "$SERVICE_PATH"
[Unit]
Description=Send Telegram notification on system shutdown or reboot
DefaultDependencies=no
After=network-online.target time-sync.target
Requires=network-online.target

[Service]
Type=oneshot
ExecStart=/bin/true
ExecStop=$SCRIPT_PATH
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF

echo "⚙️ Enabling systemd service..."
systemctl daemon-reload
systemctl enable telegram-shutdown-notify.service

echo ""
echo "------------------------------------------"
echo "🧪 Testing script manually..."
"$SCRIPT_PATH"

if [ $? -eq 0 ]; then
  echo "✅ Success! Test message sent to Telegram."
  echo "🚀 The service is ready and will run automatically on shutdown or reboot."
else
  echo "⚠️ Script executed, but curl failed. Check network or credentials in $CONFIG_FILE."
fi
