vitorpy's Dotfiles
1#!/bin/bash
2
3# Automatic timezone detection based on IP geolocation
4# Updates system timezone if it differs from detected location
5
6LOG_FILE="$HOME/.local/share/auto-timezone.log"
7CACHE_FILE="$HOME/.cache/detected-timezone"
8MAX_AGE=3600 # Cache for 1 hour
9
10# Function to log messages
11log() {
12 echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
13}
14
15# Function to get timezone from IP geolocation
16get_timezone_from_ip() {
17 # Using ipapi.co which doesn't require an API key
18 local tz=$(curl -s --connect-timeout 5 --max-time 10 "https://ipapi.co/timezone/" 2>/dev/null)
19
20 if [ -n "$tz" ] && [ "$tz" != "Undefined" ]; then
21 echo "$tz"
22 return 0
23 fi
24
25 # Fallback to ip-api.com
26 tz=$(curl -s --connect-timeout 5 --max-time 10 "http://ip-api.com/line/?fields=timezone" 2>/dev/null)
27
28 if [ -n "$tz" ] && [ "$tz" != "Undefined" ]; then
29 echo "$tz"
30 return 0
31 fi
32
33 return 1
34}
35
36# Check if cache exists and is recent
37if [ -f "$CACHE_FILE" ]; then
38 cache_age=$(($(date +%s) - $(stat -c %Y "$CACHE_FILE" 2>/dev/null || echo 0)))
39 if [ $cache_age -lt $MAX_AGE ]; then
40 log "Using cached timezone (age: ${cache_age}s)"
41 exit 0
42 fi
43fi
44
45# Get current system timezone
46current_tz=$(timedatectl show --property=Timezone --value)
47
48# Detect timezone from IP
49detected_tz=$(get_timezone_from_ip)
50
51if [ -z "$detected_tz" ]; then
52 log "Failed to detect timezone from IP"
53 exit 1
54fi
55
56log "Detected timezone: $detected_tz (current: $current_tz)"
57
58# Update if different
59if [ "$detected_tz" != "$current_tz" ]; then
60 log "Updating timezone from $current_tz to $detected_tz"
61
62 # Update timezone
63 timedatectl set-timezone "$detected_tz" 2>&1 | tee -a "$LOG_FILE"
64
65 if [ $? -eq 0 ]; then
66 log "Timezone updated successfully"
67 echo "$detected_tz" > "$CACHE_FILE"
68
69 # Trigger waybar reload to update clock
70 pkill -RTMIN+1 waybar 2>/dev/null
71 else
72 log "Failed to update timezone"
73 exit 1
74 fi
75else
76 log "Timezone unchanged"
77 echo "$detected_tz" > "$CACHE_FILE"
78fi