#!/usr/bin/env bash

#########################################################################################
#### deploy-password-expiry-timer.sh — Deploy password expiry desktop notifications  ####
#### Sets up systemd user timer + /etc/bashrc integration for all users.             ####
####                                                                                 ####
#### Author: Phil Connor                                                             ####
#### Contact: contact@mylinux.work                                                   ####
#### License: MIT                                                                    ####
#### Version 1.00                                                                    ####
####                                                                                 ####
#### Usage:                                                                          ####
####   sudo ./deploy-password-expiry-timer.sh                                        ####
####   sudo ./deploy-password-expiry-timer.sh --dry-run                              ####
####   sudo ./deploy-password-expiry-timer.sh --remove                               ####
####                                                                                 ####
#### See --help for all options.                                                     ####
#########################################################################################

set -euo pipefail

DRY_RUN=false
REMOVE=false
SCRIPT_PATH="/usr/local/bin/password-expiry-check.sh"
SCRIPT_URL="https://mylinux.work/downloads/password-expiry-check.sh"

# ── Colors ────────────────────────────────────────────────────────────
if [[ -t 1 ]]; then
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[0;33m'
    BOLD='\033[1m'
    RESET='\033[0m'
else
    RED="" GREEN="" YELLOW="" BOLD="" RESET=""
fi

log()  { echo -e "${GREEN}[OK]${RESET}    $*"; }
warn() { echo -e "${YELLOW}[WARN]${RESET}  $*"; }
err()  { echo -e "${RED}[ERROR]${RESET} $*" >&2; }
info() { echo -e "${BOLD}[INFO]${RESET}  $*"; }

# ── Usage ─────────────────────────────────────────────────────────────
usage() {
    cat <<EOF
Usage: $(basename "$0") [OPTIONS]

Deploy password expiry notifications for all users on this system.

Installs:
  1. password-expiry-check.sh to /usr/local/bin/
  2. Systemd user timer — runs every 4 hours, fires desktop popup via notify-send
  3. /etc/bashrc entry — shows terminal warning on every new shell (quiet mode)
  4. XDG autostart — fires desktop popup on graphical login

Options:
  --dry-run     Show what would be done without making changes
  --remove      Remove all deployed components
  -h, --help    Show this help
EOF
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        --dry-run)  DRY_RUN=true ;;
        --remove)   REMOVE=true ;;
        -h|--help)  usage; exit 0 ;;
        *)          err "Unknown option: $1"; usage; exit 1 ;;
    esac
    shift
done

if [[ $EUID -ne 0 ]]; then
    err "Must run as root (sudo)"
    exit 1
fi

BASHRC_LINE="# Password expiry check (quiet mode — only warns when near expiry)"
BASHRC_EXEC="${SCRIPT_PATH} -q 2>/dev/null"
BASHRC_MARKER="# password-expiry-check"

# ── Remove mode ───────────────────────────────────────────────────────
if [[ "$REMOVE" == "true" ]]; then
    info "Removing password expiry timer deployment..."
    echo ""

    # Disable global timer
    if [[ "$DRY_RUN" == "true" ]]; then
        info "Would run: systemctl --global disable password-expiry-check.timer"
    else
        systemctl --global disable password-expiry-check.timer 2>/dev/null && \
            log "Disabled global user timer" || info "Timer was not enabled"
    fi

    # Remove systemd files
    for f in /etc/systemd/user/password-expiry-check.service /etc/systemd/user/password-expiry-check.timer; do
        if [[ -f "$f" ]]; then
            if [[ "$DRY_RUN" == "true" ]]; then
                info "Would remove: $f"
            else
                rm -f "$f"
                log "Removed $f"
            fi
        fi
    done

    # Remove XDG autostart
    if [[ -f /etc/xdg/autostart/password-expiry-check.desktop ]]; then
        if [[ "$DRY_RUN" == "true" ]]; then
            info "Would remove: /etc/xdg/autostart/password-expiry-check.desktop"
        else
            rm -f /etc/xdg/autostart/password-expiry-check.desktop
            log "Removed XDG autostart"
        fi
    fi

    # Remove bashrc entry
    if grep -q "$BASHRC_MARKER" /etc/bashrc 2>/dev/null; then
        if [[ "$DRY_RUN" == "true" ]]; then
            info "Would remove password-expiry lines from /etc/bashrc"
        else
            sed -i "/${BASHRC_MARKER}/d" /etc/bashrc
            sed -i "/password-expiry-check/d" /etc/bashrc
            log "Removed /etc/bashrc entry"
        fi
    fi

    echo ""
    if [[ "$DRY_RUN" != "true" ]]; then
        log "Removal complete. Script left at ${SCRIPT_PATH} (remove manually if desired)"
    fi
    exit 0
fi

# ── Install mode ──────────────────────────────────────────────────────
info "Deploying password expiry notifications..."
echo ""

# 1. Install script
if [[ -f "$SCRIPT_PATH" ]]; then
    info "Script already exists at ${SCRIPT_PATH}"
else
    if [[ "$DRY_RUN" == "true" ]]; then
        info "Would download ${SCRIPT_URL} to ${SCRIPT_PATH}"
    else
        if command -v curl &>/dev/null; then
            curl -sSL -o "$SCRIPT_PATH" "$SCRIPT_URL"
        elif command -v wget &>/dev/null; then
            wget -q -O "$SCRIPT_PATH" "$SCRIPT_URL"
        else
            err "Neither curl nor wget found — copy password-expiry-check.sh to ${SCRIPT_PATH} manually"
            exit 1
        fi
        chmod +x "$SCRIPT_PATH"
        log "Installed ${SCRIPT_PATH}"
    fi
fi

# 2. Systemd user service
SERVICE_CONTENT="[Unit]
Description=Password Expiry Checker
After=graphical-session.target

[Service]
Type=oneshot
ExecStart=${SCRIPT_PATH} -q
Environment=DISPLAY=:0"

if [[ "$DRY_RUN" == "true" ]]; then
    info "Would create: /etc/systemd/user/password-expiry-check.service"
else
    mkdir -p /etc/systemd/user
    echo "$SERVICE_CONTENT" > /etc/systemd/user/password-expiry-check.service
    log "Created /etc/systemd/user/password-expiry-check.service"
fi

# 3. Systemd user timer — every 4 hours
TIMER_CONTENT="[Unit]
Description=Check password expiry every 4 hours

[Timer]
OnStartupSec=60
OnUnitActiveSec=4h
Persistent=true

[Install]
WantedBy=timers.target"

if [[ "$DRY_RUN" == "true" ]]; then
    info "Would create: /etc/systemd/user/password-expiry-check.timer"
    info "Would run: systemctl --global enable password-expiry-check.timer"
else
    echo "$TIMER_CONTENT" > /etc/systemd/user/password-expiry-check.timer
    log "Created /etc/systemd/user/password-expiry-check.timer"

    systemctl --global enable password-expiry-check.timer 2>/dev/null
    log "Enabled timer globally for all users"
fi

# 4. XDG autostart (graphical login trigger with delay)
DESKTOP_CONTENT="[Desktop Entry]
Type=Application
Name=Password Expiry Checker
Comment=Check password expiry on login
Exec=bash -c 'sleep 10 && ${SCRIPT_PATH} -q'
Terminal=false
NoDisplay=true
X-GNOME-Autostart-enabled=true"

if [[ "$DRY_RUN" == "true" ]]; then
    info "Would create: /etc/xdg/autostart/password-expiry-check.desktop"
else
    mkdir -p /etc/xdg/autostart
    echo "$DESKTOP_CONTENT" > /etc/xdg/autostart/password-expiry-check.desktop
    log "Created /etc/xdg/autostart/password-expiry-check.desktop"
fi

# 5. /etc/bashrc entry (terminal warning)
if grep -q "$BASHRC_MARKER" /etc/bashrc 2>/dev/null; then
    info "/etc/bashrc entry already exists"
else
    if [[ "$DRY_RUN" == "true" ]]; then
        info "Would add to /etc/bashrc:"
        echo "    ${BASHRC_LINE}"
        echo "    ${BASHRC_EXEC}"
    else
        {
            echo ""
            echo "$BASHRC_LINE"
            echo "$BASHRC_EXEC  ${BASHRC_MARKER}"
        } >> /etc/bashrc
        log "Added /etc/bashrc entry"
    fi
fi

echo ""
echo -e "${BOLD}Deployment summary:${RESET}"
echo "  • Script:       ${SCRIPT_PATH}"
echo "  • Timer:        /etc/systemd/user/password-expiry-check.timer (every 4h)"
echo "  • XDG autostart: /etc/xdg/autostart/password-expiry-check.desktop (login + 10s delay)"
echo "  • Terminal:     /etc/bashrc (quiet mode — warns only when near expiry)"
echo ""
echo -e "${BOLD}Users will see warnings via:${RESET}"
echo "  • Desktop popup every 4 hours (systemd timer)"
echo "  • Desktop popup on graphical login (XDG autostart)"
echo "  • Terminal banner on every new shell (bashrc)"
echo ""
info "Test with: ${SCRIPT_PATH} --test"
info "Remove with: $(basename "$0") --remove"
