/
/
/
1#!/bin/bash
2# ==============================================================================
3# Nginx Proxy Manager Helper Script
4# ==============================================================================
5#
6# Description: Maintenance and helper functions for Nginx Proxy Manager
7# Usage: ./nginx-proxy-helper.sh [cleanup|certs|backup|stats|optimize]
8#
9# This script is automatically generated by Ansible - DO NOT EDIT MANUALLY
10# Template: nginx-proxy-helper.sh.j2
11#
12# ==============================================================================
13
14set -euo pipefail
15
16# Configuration
17NGINX_DATA_DIR="{{ docker_base_path }}/nginx-proxy/data"
18NGINX_LETSENCRYPT_DIR="{{ docker_base_path }}/nginx-proxy/letsencrypt"
19NGINX_LOGS_DIR="{{ docker_base_path }}/nginx-proxy/logs"
20BACKUP_DIR="{{ docker_base_path }}/backups/nginx-proxy"
21LOG_FILE="/var/log/nginx-proxy-helper.log"
22
23# Container names
24NGINX_CONTAINER="{{ nginx_proxy_container_name }}"
25DB_CONTAINER="{{ nginx_proxy_db_container_name }}"
26
27# Retention settings
28LOG_RETENTION_DAYS=30
29BACKUP_RETENTION_DAYS=7
30CACHE_CLEANUP_DAYS=7
31
32# Logging function
33log() {
34 echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "${LOG_FILE}"
35}
36
37# Error handling function
38error_exit() {
39 log "ERROR: $1"
40 exit 1
41}
42
43# Check if container is running
44container_running() {
45 docker inspect -f '{{.State.Running}}' "$1" 2>/dev/null | grep -q "true"
46}
47
48# Cleanup old logs and temporary files
49cleanup_files() {
50 log "Starting cleanup of Nginx Proxy Manager files"
51
52 # Cleanup old log files
53 if [[ -d "${NGINX_LOGS_DIR}" ]]; then
54 local logs_removed=$(find "${NGINX_LOGS_DIR}" -name "*.log*" -mtime +${LOG_RETENTION_DAYS} -delete -print | wc -l)
55 log "Removed ${logs_removed} old log files"
56 fi
57
58 # Cleanup temporary files
59 if [[ -d "${NGINX_DATA_DIR}" ]]; then
60 local temp_files_removed=$(find "${NGINX_DATA_DIR}" -name "*.tmp" -delete -print | wc -l)
61 log "Removed ${temp_files_removed} temporary files"
62
63 # Cleanup cache files
64 local cache_files_removed=$(find "${NGINX_DATA_DIR}" -name "cache*" -mtime +${CACHE_CLEANUP_DAYS} -delete -print | wc -l)
65 log "Removed ${cache_files_removed} old cache files"
66 fi
67
68 # Cleanup backup files
69 if [[ -d "${BACKUP_DIR}" ]]; then
70 local backups_removed=$(find "${BACKUP_DIR}" -name "*.tar.gz" -mtime +${BACKUP_RETENTION_DAYS} -delete -print | wc -l)
71 log "Removed ${backups_removed} old backup files"
72 fi
73
74 log "Cleanup completed"
75}
76
77# Check and renew SSL certificates
78manage_certificates() {
79 log "Checking SSL certificates"
80
81 if ! container_running "${NGINX_CONTAINER}"; then
82 error_exit "Nginx container is not running"
83 fi
84
85 # Check certificate expiration
86 local certs_checked=0
87 local certs_expiring=0
88
89 find "${NGINX_LETSENCRYPT_DIR}" -name "cert.pem" -type f 2>/dev/null | while read cert; do
90 certs_checked=$((certs_checked + 1))
91
92 local expiry_date=$(openssl x509 -enddate -noout -in "${cert}" 2>/dev/null | cut -d= -f2)
93 if [[ -n "${expiry_date}" ]]; then
94 local expiry_epoch=$(date -d "${expiry_date}" +%s 2>/dev/null || echo 0)
95 local now_epoch=$(date +%s)
96 local days_until_expiry=$(( (expiry_epoch - now_epoch) / 86400 ))
97
98 if [[ ${days_until_expiry} -lt 7 ]]; then
99 certs_expiring=$((certs_expiring + 1))
100 local domain=$(basename "$(dirname "$(dirname "${cert}")")")
101 log "WARNING: Certificate for ${domain} expires in ${days_until_expiry} days"
102 fi
103 fi
104 done
105
106 log "Certificate check completed: ${certs_checked} certificates checked, ${certs_expiring} expiring soon"
107
108 # Attempt certificate renewal if any are expiring
109 if [[ ${certs_expiring} -gt 0 ]]; then
110 log "Attempting certificate renewal"
111
112 # Send SIGHUP to Nginx to trigger certificate renewal
113 docker kill --signal="SIGHUP" "${NGINX_CONTAINER}" 2>/dev/null || true
114 sleep 5
115
116 log "Certificate renewal signal sent"
117 fi
118}
119
120# Create quick configuration backup
121quick_backup() {
122 local backup_file="${BACKUP_DIR}/nginx-config-backup-$(date +%Y%m%d-%H%M%S).tar.gz"
123
124 log "Creating quick configuration backup"
125
126 mkdir -p "${BACKUP_DIR}"
127
128 # Backup critical configuration files
129 tar -czf "${backup_file}" \
130 -C "${NGINX_DATA_DIR}" \
131 nginx \
132 certificates \
133 config.json \
134 2>/dev/null || true
135
136 if [[ -f "${backup_file}" ]]; then
137 log "Quick backup created: ${backup_file}"
138 echo "Backup size: $(du -h "${backup_file}" | cut -f1)"
139 else
140 error_exit "Failed to create quick backup"
141 fi
142}
143
144# Show statistics and status
145show_stats() {
146 log "Nginx Proxy Manager Statistics"
147
148 # Container status
149 echo "=== Container Status ==="
150 for container in "${NGINX_CONTAINER}" "${DB_CONTAINER}"; do
151 if container_running "${container}"; then
152 local status=$(docker inspect -f '{{.State.Status}}' "${container}")
153 local restarts=$(docker inspect -f '{{.RestartCount}}' "${container}")
154 echo "${container}: ${status} (restarts: ${restarts})"
155 else
156 echo "${container}: NOT RUNNING"
157 fi
158 done
159
160 echo ""
161
162 # Certificate statistics
163 echo "=== Certificate Statistics ==="
164 local total_certs=$(find "${NGINX_LETSENCRYPT_DIR}" -name "cert.pem" -type f 2>/dev/null | wc -l)
165 echo "Total SSL certificates: ${total_certs}"
166
167 # Proxy host statistics
168 if [[ -f "${NGINX_DATA_DIR}/config.json" ]]; then
169 local proxy_hosts=$(jq '.proxy_hosts | length' "${NGINX_DATA_DIR}/config.json" 2>/dev/null || echo "0")
170 local redirection_hosts=$(jq '.redirection_hosts | length' "${NGINX_DATA_DIR}/config.json" 2>/dev/null || echo "0")
171 local dead_hosts=$(jq '.dead_hosts | length' "${NGINX_DATA_DIR}/config.json" 2>/dev/null || echo "0")
172
173 echo "Proxy hosts: ${proxy_hosts}"
174 echo "Redirection hosts: ${redirection_hosts}"
175 echo "Dead hosts: ${dead_hosts}"
176 fi
177
178 echo ""
179
180 # Disk usage
181 echo "=== Disk Usage ==="
182 du -sh "${NGINX_DATA_DIR}" 2>/dev/null || true
183 du -sh "${NGINX_LETSENCRYPT_DIR}" 2>/dev/null || true
184 du -sh "${NGINX_LOGS_DIR}" 2>/dev/null || true
185
186 echo ""
187
188 # Database statistics
189 if container_running "${DB_CONTAINER}"; then
190 echo "=== Database Statistics ==="
191 docker exec "${DB_CONTAINER}" mysql -u "{{ nginx_proxy_db_user }}" -p"{{ nginx_proxy_db_password }}" "{{ nginx_proxy_db_name }}" \
192 -e "SELECT TABLE_NAME, TABLE_ROWS, DATA_LENGTH, INDEX_LENGTH FROM information_schema.TABLES WHERE TABLE_SCHEMA = '{{ nginx_proxy_db_name }}'" \
193 2>/dev/null || true
194 fi
195}
196
197# Optimize Nginx configuration
198optimize_config() {
199 log "Optimizing Nginx configuration"
200
201 if ! container_running "${NGINX_CONTAINER}"; then
202 error_exit "Nginx container is not running"
203 fi
204
205 # Test current configuration
206 if docker exec "${NGINX_CONTAINER}" nginx -t; then
207 log "Current Nginx configuration is valid"
208 else
209 error_exit "Current Nginx configuration is invalid"
210 fi
211
212 # Reload Nginx to apply any configuration changes
213 log "Reloading Nginx configuration"
214 docker exec "${NGINX_CONTAINER}" nginx -s reload 2>/dev/null || true
215
216 # Wait for reload to complete
217 sleep 2
218
219 # Check if reload was successful
220 if docker exec "${NGINX_CONTAINER}" nginx -t; then
221 log "Nginx configuration reloaded successfully"
222 else
223 error_exit "Nginx configuration reload failed"
224 fi
225
226 # Optimize database if running
227 if container_running "${DB_CONTAINER}"; then
228 log "Optimizing database tables"
229 docker exec "${DB_CONTAINER}" mysqlcheck -u "{{ nginx_proxy_db_user }}" -p"{{ nginx_proxy_db_password }}" \
230 --optimize "{{ nginx_proxy_db_name }}" 2>/dev/null || true
231 fi
232
233 log "Optimization completed"
234}
235
236# Show usage
237usage() {
238 cat << EOF
239Nginx Proxy Manager Helper Script
240
241Usage: $0 [command]
242
243Commands:
244 cleanup Cleanup old logs, temp files, and backups
245 certs Check and manage SSL certificates
246 backup Create quick configuration backup
247 stats Show statistics and status
248 optimize Optimize Nginx configuration and database
249 help Show this help message
250
251Examples:
252 $0 cleanup
253 $0 certs
254 $0 backup
255 $0 stats
256 $0 optimize
257
258Retention Settings:
259 Log files: ${LOG_RETENTION_DAYS} days
260 Backups: ${BACKUP_RETENTION_DAYS} days
261 Cache files: ${CACHE_CLEANUP_DAYS} days
262EOF
263}
264
265# Main execution
266main() {
267 local command="${1:-help}"
268
269 case "${command}" in
270 cleanup)
271 cleanup_files
272 ;;
273 certs)
274 manage_certificates
275 ;;
276 backup)
277 quick_backup
278 ;;
279 stats)
280 show_stats
281 ;;
282 optimize)
283 optimize_config
284 ;;
285 help|*)
286 usage
287 ;;
288 esac
289}
290
291# Run main function with all arguments
292main "$@"