#!/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-boot-notify.sh"
SERVICE_PATH="/etc/systemd/system/telegram-boot-notify.service"

echo "=========================================="
echo "  Telegram Boot Notification Installer"
echo "=========================================="
echo ""

# Function to validate the config file
validate_config() {
  if [ -f "$CONFIG_FILE" ]; then
    # Load config file
    source "$CONFIG_FILE" 2>/dev/null

    if [ -n "$TELEGRAM_BOT_TOKEN" ] && [ -n "$TELEGRAM_CHAT_ID" ]; then
      return 0
    fi
  fi
  return 1
}

# Check existence and validity of /etc/telegram.conf
if validate_config; then
  echo "✅ Valid configuration found at $CONFIG_FILE"
  echo "   - Chat ID: $TELEGRAM_CHAT_ID"
else
  echo "⚠️ Configuration file $CONFIG_FILE missing or invalid."
  echo "Setting up a new configuration file..."
  echo ""

  read -p "Enter your Telegram Bot Token: " BOT_TOKEN_INPUT
  read -p "Enter your Telegram Chat ID: " CHAT_ID_INPUT

  if [ -z "$BOT_TOKEN_INPUT" ] || [ -z "$CHAT_ID_INPUT" ]; then
    echo "❌ Error: Both Bot Token and Chat ID are required."
    exit 1
  fi

  # Write configuration file
  cat << EOF > "$CONFIG_FILE"
# Telegram Alert Configuration
TELEGRAM_CHAT_ID="$CHAT_ID_INPUT"
TELEGRAM_BOT_TOKEN="$BOT_TOKEN_INPUT"
EOF

  chmod 600 "$CONFIG_FILE"
  echo "✅ Created $CONFIG_FILE (permissions restricted to root)."
fi

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

# Write the main notification script reading from /etc/telegram.conf
cat << 'EOF' > "$SCRIPT_PATH"
#!/bin/bash

CONFIG_FILE="/etc/telegram.conf"

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

# 1. Wait up to 30 seconds for an actual IPv4 address to be assigned to a real network interface
MAX_RETRIES=15
RETRY_COUNT=0
LOCAL_IP=""

until [ -n "$LOCAL_IP" ] || [ $RETRY_COUNT -ge $MAX_RETRIES ]; do
  LOCAL_IP=$(ip -4 -o addr show scope global 2>/dev/null | \
    grep -vE 'docker|veth|br-|tun|tap|tailscale|wg|cni|flannel|dummy' | \
    awk '{print $4}' | cut -d/ -f1 | head -n1)

  if [ -z "$LOCAL_IP" ]; then
    sleep 2
    ((RETRY_COUNT++))
  fi
done

[ -z "$LOCAL_IP" ] && LOCAL_IP="Unavailable"

# 2. Wait for internet connectivity to hit Telegram API
RETRY_COUNT=0
until ping -c 1 api.telegram.org >/dev/null 2>&1 || [ $RETRY_COUNT -ge 10 ]; do
  sleep 2
  ((RETRY_COUNT++))
done

# 3. Gather System Details
PUBLIC_IP=$(curl -s --max-time 10 https://ifconfig.me || echo "Unavailable")
DATE_TIME=$(date "+%Y-%m-%d %H:%M:%S %Z")
HOSTNAME=$(hostname)

MESSAGE="🚀 *Server Boot Notification*

🖥 *Host:* \`$HOSTNAME\`
📅 *Date & Time:* \`$DATE_TIME\`

📡 *IP Addresses:*
• *Local IP:* \`$LOCAL_IP\`
• *Public IP:* \`$PUBLIC_IP\`"

# 4. Send Message via Telegram
curl --retry 5 --retry-delay 2 --retry-connrefused -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..."

cat << EOF > "$SERVICE_PATH"
[Unit]
Description=Send Telegram notification with IP address on startup
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
ExecStart=$SCRIPT_PATH
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF

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

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

if [ $? -eq 0 ]; then
  echo "✅ Success! Check your Telegram channel/chat for the test message."
  echo "🚀 The service will now run automatically on every boot."
else
  echo "⚠️ Failed to send Telegram notification. Check credentials in $CONFIG_FILE."
fi
