diff --git a/.env b/.env deleted file mode 100644 index 6641729..0000000 --- a/.env +++ /dev/null @@ -1,4 +0,0 @@ -SERVER_NAME=delemaco -SERVER_USER=root -MAC_ADDRESS=b8:cb:29:a1:f3:88 -PORT=8080 diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b4a8249..3dd69d0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -2,205 +2,137 @@ name: Build and Release on: push: - branches: [ main ] + branches: [main] pull_request: - branches: [ main ] + branches: [main] jobs: build: - name: Cross-compile for Raspberry Pi + name: Build multi-arch Raspberry Pi binaries runs-on: ubuntu-latest steps: - - name: Checkout code - uses: actions/checkout@v3 + - name: Checkout code + uses: actions/checkout@v4 - - name: Set up Go - uses: actions/setup-go@v4 - with: - go-version: '1.20' + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: "1.22" - - name: Build for ARM (Pi Zero, Pi 1 - ARMv6) - run: | - GOOS=linux GOARCH=arm GOARM=6 go build -ldflags="-s -w" -o wol-server-arm6 + - name: Build for ARMv6 (Pi Zero / Pi 1) + run: | + GOOS=linux GOARCH=arm GOARM=6 \ + go build -ldflags="-s -w" -o wol-server-armv6 - - name: Create systemd service file - run: | - cat > wol-server.service << 'EOL' - [Unit] - Description=WOL Server Go Application - After=network.target + - name: Build for ARM64 (Pi Zero 2 / Pi 3 / Pi 4 / Pi 5) + run: | + GOOS=linux GOARCH=arm64 \ + go build -ldflags="-s -w" -o wol-server-arm64 - [Service] - User=pi - WorkingDirectory=/home/pi/wol-server - ExecStart=/home/pi/wol-server/wol-server - Restart=always + - name: Create systemd service file + run: | + cat > wol-server.service << 'EOF' + [Unit] + Description=WOL Server Go Application + After=network.target - [Install] - WantedBy=multi-user.target - EOL + [Service] + Type=simple + User=loke + WorkingDirectory=/home/loke/wol-server + ExecStart=/home/loke/wol-server/wol-server + Restart=always + RestartSec=3 - - name: Create deployment script - run: | - cat > install.sh << 'EOL' - #!/bin/bash - set -e + [Install] + WantedBy=multi-user.target + EOF - # Installation directory - INSTALL_DIR=~/wol-server + - name: Create install script + run: | + cat > install.sh << 'EOF' + #!/bin/bash + set -e - echo "Creating installation directory..." - mkdir -p $INSTALL_DIR - mkdir -p $INSTALL_DIR/templates + INSTALL_DIR="$HOME/wol-server" - echo "Installing application..." - cp wol-server-arm6 $INSTALL_DIR/wol-server - chmod +x $INSTALL_DIR/wol-server + echo "Creating installation directory..." + mkdir -p "$INSTALL_DIR/templates" - echo "Installing template files..." - cp -r templates/* $INSTALL_DIR/templates/ + ARCH=$(uname -m) + case "$ARCH" in + armv6l|armv7l) + BIN="wol-server-armv6" + ;; + aarch64) + BIN="wol-server-arm64" + ;; + *) + echo "Unsupported architecture: $ARCH" + exit 1 + ;; + esac - echo "Installing system service..." - sudo cp wol-server.service /etc/systemd/system/ - sudo systemctl daemon-reload - sudo systemctl enable wol-server + echo "Detected architecture: $ARCH" + echo "Using binary: $BIN" - # Install required dependencies - echo "Installing dependencies..." - sudo apt-get update -qq - sudo apt-get install -y wakeonlan sshpass + cp "$BIN" "$INSTALL_DIR/wol-server" + chmod +x "$INSTALL_DIR/wol-server" - # Start the service - echo "Starting service..." - sudo systemctl restart wol-server + echo "Installing templates..." + cp -r templates/* "$INSTALL_DIR/templates/" - echo "===========================================" - echo "Installation complete!" - echo "The WOL server is now running at http://$(hostname -I | awk '{print $1}'):8080" - echo "===========================================" - EOL + echo "Installing systemd service..." + sudo cp wol-server.service /etc/systemd/system/ + sudo systemctl daemon-reload + sudo systemctl enable wol-server - chmod +x install.sh + echo "Installing dependencies..." + sudo apt-get update -qq + sudo apt-get install -y wakeonlan sshpass - - name: Create README with installation instructions - run: | - cat > INSTALL.md << 'EOL' - # WOL Server Installation Guide + echo "Starting service..." + sudo systemctl restart wol-server - This guide will help you install the Wake-on-LAN server on your Raspberry Pi. + echo "===========================================" + echo "WOL Server installed successfully!" + echo "URL: http://$(hostname -I | awk '{print $1}'):8080" + echo "===========================================" + EOF - ## Prerequisites + chmod +x install.sh - - Raspberry Pi running Raspberry Pi OS (Raspbian) - - SSH access to your Pi - - SCP or SFTP capability to transfer files + - name: Create release package + run: | + mkdir -p package + cp wol-server-armv6 package/ + cp wol-server-arm64 package/ + cp wol-server.service package/ + cp install.sh package/ + cp -r templates package/ - ## Installation Steps + tar -czf wol-server.tar.gz -C package . - ### 1. Transfer Files to Raspberry Pi + - name: Create Forgejo Release + if: github.ref == 'refs/heads/main' + run: | + TAG="v${{ github.run_number }}" + API_URL="${{ github.server_url }}/api/v1" + REPO="${{ github.repository }}" - **Option 1: Using SCP from your computer** + # Create release + RELEASE_ID=$(curl -s -X POST \ + -H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \ + -H "Content-Type: application/json" \ + "${API_URL}/repos/${REPO}/releases" \ + -d "{\"tag_name\": \"${TAG}\", \"name\": \"Release ${TAG}\", \"draft\": false, \"prerelease\": false}" \ + | grep -o '"id":[0-9]*' | head -1 | cut -d: -f2) - ```bash - # Replace with your Pi's IP address - PI_IP=192.168.1.100 + # Upload asset + curl -s -X POST \ + -H "Authorization: token ${{ secrets.GITEA_TOKEN }}" \ + "${API_URL}/repos/${REPO}/releases/${RELEASE_ID}/assets?name=wol-server.tar.gz" \ + -F "attachment=@wol-server.tar.gz" > /dev/null - # Transfer the installation package - scp wol-server.tar.gz pi@$PI_IP:~/ - ``` - - **Option 2: Using SFTP client** - - Use a tool like FileZilla, WinSCP, or Cyberduck to transfer the `wol-server.tar.gz` file to your Raspberry Pi. - - ### 2. SSH into your Raspberry Pi - - ```bash - ssh pi@192.168.1.100 - ``` - - ### 3. Extract and Install - - ```bash - # Navigate to home directory - cd ~ - - # Extract the archive - tar -xzf wol-server.tar.gz - - # Run the installation script - ./install.sh - ``` - - ### 4. Test the Installation - - Open a web browser and navigate to: - ``` - http://[your-pi-ip]:8080 - ``` - - ## Troubleshooting - - If the service fails to start, check the logs: - ```bash - sudo systemctl status wol-server - ``` - - If template errors occur, ensure the template files were copied correctly: - ```bash - ls -la ~/wol-server/templates/ - ``` - - ## Manual Installation (if needed) - - If you encounter issues with the automated install: - - ```bash - # Create directories - mkdir -p ~/wol-server/templates - - # Copy files manually - cp wol-server-arm6 ~/wol-server/wol-server - chmod +x ~/wol-server/wol-server - cp templates/* ~/wol-server/templates/ - sudo cp wol-server.service /etc/systemd/system/ - - # Install dependencies - sudo apt-get update - sudo apt-get install -y wakeonlan sshpass - - # Enable and start service - sudo systemctl daemon-reload - sudo systemctl enable wol-server - sudo systemctl start wol-server - ``` - EOL - - - name: Create all-in-one package - run: | - # Create a single package with everything needed - mkdir -p package - cp wol-server-arm6 package/ - cp wol-server.service package/ - cp install.sh package/ - cp -r templates package/ - cp INSTALL.md package/ - - # Create the tarball - tar -czf wol-server.tar.gz -C package . - - - name: Create Release - id: create_release - uses: softprops/action-gh-release@v1 - if: github.ref == 'refs/heads/main' - with: - tag_name: v${{ github.run_number }} - name: Release v${{ github.run_number }} - draft: false - prerelease: false - files: | - wol-server.tar.gz - INSTALL.md - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + echo "Release ${TAG} created with asset wol-server.tar.gz" diff --git a/main.go b/main.go index 6de0d76..d4b78c6 100644 --- a/main.go +++ b/main.go @@ -296,21 +296,19 @@ func verifyScheduleConfig() { return } - // Immediately check if we need to boot based on the current time + // Immediately check if we need to boot ONLY at exact start time now := time.Now() currentTimeStr := now.Format("15:04") - // Check if we're within the schedule window (between start and end time) - if currentTimeStr == scheduleConfig.StartTime { - log.Printf("STARTUP MATCH: Current time %s matches start time, attempting boot", currentTimeStr) + // Check ONLY if current time EXACTLY matches start time + if currentTimeStr == scheduleConfig.StartTime && ShouldRunToday(now) { + log.Printf("STARTUP MATCH: Current time %s matches start time EXACTLY, attempting boot", currentTimeStr) if !isServerOnline() { sendWakeOnLAN() - } - } else if currentTimeStr > scheduleConfig.StartTime && currentTimeStr < scheduleConfig.EndTime { - log.Printf("STARTUP CHECK: Current time %s is within schedule window, checking server", currentTimeStr) - if !isServerOnline() { - log.Printf("Server should be online based on schedule - attempting boot") - sendWakeOnLAN() + // Mark that the server was started by the scheduler + scheduleConfig.StartedBySchedule = true + scheduleConfig.LastRun = now.Format(time.RFC3339) + UpdateScheduleConfig(scheduleConfig) } } @@ -337,88 +335,88 @@ func verifyScheduleConfig() { func runScheduleChecker() { // Define the checkScheduleOnce function checkScheduleOnce := func() { - // Check if server should be on according to schedule - shouldBeOn := CheckSchedule() + // Only check exact times for schedule actions, don't use window logic + now := time.Now() + currentTimeStr := now.Format("15:04") serverIsOn := isServerOnline() // Log schedule status (debug level) if scheduleConfig.Enabled { - log.Printf("Schedule check: Window active=%v, Server online=%v", shouldBeOn, serverIsOn) + log.Printf("Schedule check: Current=%s, Start=%s, End=%s, LastRun=%s", + currentTimeStr, scheduleConfig.StartTime, scheduleConfig.EndTime, scheduleConfig.LastRun) - // Force check the current time against the schedule time - now := time.Now() - currentTimeStr := now.Format("15:04") - if currentTimeStr == scheduleConfig.StartTime { - log.Printf("EXACT TIME MATCH! Current time %s equals start time", currentTimeStr) - shouldBeOn = true - } else if currentTimeStr == scheduleConfig.EndTime { - log.Printf("EXACT END TIME MATCH! Current time %s equals end time", currentTimeStr) - shouldBeOn = false - } - } + // Only act at exact start or end times + // EXACT START TIME MATCH - Try to boot server + if currentTimeStr == scheduleConfig.StartTime && !serverIsOn && ShouldRunToday(now) { + log.Println("EXACT START TIME: Initiating boot sequence...") - if shouldBeOn && !serverIsOn { - log.Println("Schedule: Server should be on but is offline. BOOT ATTEMPT INITIATED...") - // Try multiple times to boot with small delays between attempts - for attempt := 1; attempt <= 3; attempt++ { - log.Printf("Boot attempt %d/3", attempt) - err := sendWakeOnLAN() - if err != nil { - log.Printf("Error booting server from schedule: %v", err) - } else { - log.Println("Schedule: Boot command sent successfully") - } - - // Check if server came online - time.Sleep(3 * time.Second) // Extended wait time for boot check - if isServerOnline() { - log.Println("Server successfully booted!") - break - } - - // Short delay before next attempt - if attempt < 3 { - time.Sleep(1 * time.Second) - } - } - } else if !shouldBeOn && serverIsOn { - // Check if auto-shutdown is enabled - if scheduleConfig.AutoShutdown && shutdownPassword != "" && scheduleConfig.StartedBySchedule { - log.Println("Schedule: Server is on outside of scheduled window - attempting auto-shutdown") - - // Try multiple times to shut down the server - var shutdownSuccessful bool + // Try multiple times to boot with small delays between attempts for attempt := 1; attempt <= 3; attempt++ { - log.Printf("Auto shutdown attempt %d/3", attempt) - err := shutdownServer(shutdownPassword) + log.Printf("Boot attempt %d/3", attempt) + err := sendWakeOnLAN() if err != nil { - log.Printf("Auto shutdown attempt %d failed: %v", attempt, err) - if attempt < 3 { - time.Sleep(3 * time.Second) - } + log.Printf("Error booting server from schedule: %v", err) } else { - log.Printf("Auto shutdown initiated successfully on attempt %d", attempt) - shutdownSuccessful = true + log.Println("Schedule: Boot command sent successfully") + // Mark that server was started by scheduler + scheduleConfig.StartedBySchedule = true + scheduleConfig.LastRun = now.Format(time.RFC3339) + UpdateScheduleConfig(scheduleConfig) + } + + // Check if server came online + time.Sleep(3 * time.Second) // Extended wait time for boot check + if isServerOnline() { + log.Println("Server successfully booted!") break } - } - if !shutdownSuccessful { - log.Printf("All auto shutdown attempts failed") + // Short delay before next attempt + if attempt < 3 { + time.Sleep(1 * time.Second) + } + } + // EXACT END TIME MATCH - Try to shutdown server + } else if currentTimeStr == scheduleConfig.EndTime && serverIsOn { + // Check if auto-shutdown is enabled + if scheduleConfig.AutoShutdown && shutdownPassword != "" && scheduleConfig.StartedBySchedule { + log.Println("EXACT END TIME: Attempting auto-shutdown") + + // Try multiple times to shut down the server + var shutdownSuccessful bool + for attempt := 1; attempt <= 3; attempt++ { + log.Printf("Auto shutdown attempt %d/3", attempt) + err := shutdownServer(shutdownPassword) + if err != nil { + log.Printf("Auto shutdown attempt %d failed: %v", attempt, err) + if attempt < 3 { + time.Sleep(3 * time.Second) + } + } else { + log.Printf("Auto shutdown initiated successfully on attempt %d", attempt) + shutdownSuccessful = true + break + } + } + + if !shutdownSuccessful { + log.Printf("All auto shutdown attempts failed") + } } - } else if !scheduleConfig.StartedBySchedule { - // Server wasn't started by scheduler - log.Println("Schedule: Server is on outside of scheduled window but was not started by scheduler") } else { - // Just log the situation when auto-shutdown is not enabled - log.Println("Schedule: Server is on outside of scheduled window") + // No action at non-exact times, just log status + if serverIsOn && scheduleConfig.StartedBySchedule && currentTimeStr > scheduleConfig.EndTime { + log.Printf("Server is still online after end time %s - waiting for next exact end time match", scheduleConfig.EndTime) + } } } - // Update last run timestamp if we're exiting the window + // Update last run timestamp if we've passed the end time // This helps track when the schedule was last active currentConfig := GetScheduleConfig() - if currentConfig.Enabled && !shouldBeOn && currentConfig.LastRun != "" { + nowTime := time.Now() + currentTimeString := nowTime.Format("15:04") + if currentConfig.Enabled && currentTimeString > currentConfig.EndTime && currentConfig.LastRun != "" { lastRun, err := time.Parse(time.RFC3339, currentConfig.LastRun) if err == nil { // If it's been more than a day since the last update, reset the timestamp diff --git a/schedule.json b/schedule.json index 1f6a9b6..a07df7d 100644 --- a/schedule.json +++ b/schedule.json @@ -1,9 +1,9 @@ { - "enabled": false, - "startTime": "", - "endTime": "", + "enabled": true, + "startTime": "13:46", + "endTime": "13:49", "frequency": "daily", - "lastRun": "", - "autoShutdown": false, - "startedBySchedule": false + "lastRun": "2025-09-05T13:46:41+02:00", + "autoShutdown": true, + "startedBySchedule": true } \ No newline at end of file diff --git a/utils.go b/utils.go index 42e3bcc..c39d4dd 100644 --- a/utils.go +++ b/utils.go @@ -10,7 +10,6 @@ import ( "os/exec" "path/filepath" "runtime" - "strings" "time" ) @@ -231,7 +230,7 @@ func CheckSchedule() (shouldBeOn bool) { // Check if the schedule should run today based on frequency // Check if we're in the schedule window - if !shouldRunToday(now) { + if !ShouldRunToday(now) { log.Printf("Schedule is active but not set to run today based on frequency: %s", scheduleConfig.Frequency) return false } @@ -282,7 +281,7 @@ func CheckSchedule() (shouldBeOn bool) { if scheduleConfig.AutoShutdown && shutdownPassword != "" && isServerOnline() { // Only shut down if the server was started by the scheduler if scheduleConfig.StartedBySchedule { - log.Printf("Auto shutdown is enabled - attempting to shut down server") + log.Printf("Auto shutdown is enabled - attempting to shut down server at end time") // Try up to 3 times to shut down the server var shutdownSuccessful bool @@ -309,8 +308,13 @@ func CheckSchedule() (shouldBeOn bool) { } } } else { - // Otherwise check if we're within the window with a small buffer (30 seconds) - shouldBeOn = (now.After(startTime.Add(-30*time.Second)) && now.Before(endTime)) + // ONLY consider the server should be on at EXACT start time or EXACT end time + shouldBeOn = (currentTimeStr == scheduleConfig.StartTime) + + // Log that we're waiting for exact times for actions + if currentTimeStr != scheduleConfig.StartTime && currentTimeStr != scheduleConfig.EndTime { + log.Printf("Not at exact schedule times - no action needed until exact start/end time") + } } log.Printf("Schedule window check: Current=%v, Start=%v, End=%v, ShouldBeOn=%v", @@ -321,39 +325,25 @@ func CheckSchedule() (shouldBeOn bool) { log.Printf("EXACT END TIME MATCH! Current time %s equals end time - schedule window should close", currentTimeStr) } - // If we're in the schedule window, update the LastRun and attempt to boot the server - if shouldBeOn { - // Only update LastRun if it hasn't been set yet for this window - if scheduleConfig.LastRun == "" { - log.Printf("Entering scheduled backup window, updating LastRun timestamp") - scheduleConfig.LastRun = now.Format(time.RFC3339) - if err := saveScheduleConfig(); err != nil { - log.Printf("Warning: Failed to save schedule config: %v", err) - } + // If we're at exact start time, update the LastRun timestamp + if currentTimeStr == scheduleConfig.StartTime && ShouldRunToday(now) { + // We only track that we've seen the start time + log.Printf("Exact start time reached - marking schedule run") - // Force a server boot attempt on window start - if !isServerOnline() { - log.Printf("Schedule window started - attempting to boot server") - if err := sendWakeOnLAN(); err != nil { - log.Printf("Schedule boot failed: %v", err) - } else { - // Mark that server was started by scheduler - scheduleConfig.StartedBySchedule = true - if err := saveScheduleConfig(); err != nil { - log.Printf("Failed to save schedule config: %v", err) - } - } - } + // Don't automatically boot the server here - let the main scheduler handle it + // We're just updating state information + scheduleConfig.LastRun = now.Format(time.RFC3339) + if err := saveScheduleConfig(); err != nil { + log.Printf("Warning: Failed to save schedule config: %v", err) } } return shouldBeOn } -// shouldRunToday checks if the schedule should run today based on frequency -func shouldRunToday(now time.Time) bool { - // Special case: if we're within the current window (between start and end time), - // we should consider the schedule to be active regardless of LastRun +// ShouldRunToday checks if the schedule should run today based on frequency +func ShouldRunToday(now time.Time) bool { + // We no longer check for windows - we only check at exact times currentTimeStr := now.Format("15:04") today := now.Format("2006-01-02") @@ -366,9 +356,9 @@ func shouldRunToday(now time.Time) bool { endTime = endTime.AddDate(0, 0, 1) } - // If we're currently in the window, allow it to run - if now.After(startTime) && now.Before(endTime) { - log.Println("Currently within today's schedule window - schedule should be active") + // Only log that we're at an exact schedule time + if currentTimeStr == scheduleConfig.StartTime { + log.Println("Currently at exact start time - schedule should be active") return true } } @@ -389,10 +379,11 @@ func shouldRunToday(now time.Time) bool { // Don't allow running multiple times on the same day unless // it's been reset explicitly (LastRun set to empty) if lastRun.Year() == now.Year() && lastRun.YearDay() == now.YearDay() { - // Check if we've passed the end time today - if so, we can reset for tomorrow + // Check if we've passed the end time today - if so, we can reset for next run if scheduleConfig.EndTime != "" && currentTimeStr > scheduleConfig.EndTime { log.Println("Current time is after end time - resetting for next run") scheduleConfig.LastRun = "" + scheduleConfig.StartedBySchedule = false // Reset this flag too saveScheduleConfig() return false } @@ -554,18 +545,6 @@ func shutdownServer(password string) error { log.Println("Using sshpass for authentication") log.Printf("Password being used: %s", password) - // Create the command - cmdArgs := []string{ - "sshpass", "-p", password, "ssh", - "-o", "StrictHostKeyChecking=no", - "-o", "UserKnownHostsFile=/dev/null", - "-o", "LogLevel=ERROR", - "-o", "ConnectTimeout=10", - fmt.Sprintf("%s@%s", serverUser, serverName), - "sudo", "-S", "shutdown", "-h", "now", - } - log.Printf("Full command: %s", strings.Join(cmdArgs, " ")) - // Add more SSH options to handle potential issues cmd := exec.Command("sshpass", "-p", password, "ssh", "-o", "StrictHostKeyChecking=no", @@ -593,18 +572,6 @@ func shutdownServer(password string) error { log.Println("Trying direct SSH with password via stdin") log.Printf("Password being used: %s", password) - // Create command args - cmdArgs := []string{ - "ssh", - "-o", "StrictHostKeyChecking=no", - "-o", "UserKnownHostsFile=/dev/null", - "-o", "LogLevel=ERROR", - "-o", "ConnectTimeout=10", - fmt.Sprintf("%s@%s", serverUser, serverName), - "sudo", "-S", "shutdown", "-h", "now", - } - log.Printf("Full command: %s", strings.Join(cmdArgs, " ")) - cmd := exec.Command("ssh", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", @@ -629,17 +596,6 @@ func shutdownServer(password string) error { log.Println("Trying simpler shutdown command as fallback") log.Printf("Password being used: %s", password) - // Create command args - cmdArgs = []string{ - "ssh", - "-o", "StrictHostKeyChecking=no", - "-o", "UserKnownHostsFile=/dev/null", - "-o", "LogLevel=ERROR", - fmt.Sprintf("%s@%s", serverUser, serverName), - "sudo", "shutdown", "now", - } - log.Printf("Full command: %s", strings.Join(cmdArgs, " ")) - cmd = exec.Command("ssh", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null",