#!/bin/bash
# Réveil musical : ouvre un lien (YouTube…) à l'heure choisie.
# Le lien est modifiable depuis l'app (menu « Changer le lien »).
OSA=/usr/bin/osascript
CONFIG_DIR="$HOME/Library/Application Support/Reveil Musical"
CONFIG_LIEN="$CONFIG_DIR/lien.txt"
FICHIER_CIBLE="/tmp/reveil-musical.cible"
RES="$(cd "$(dirname "$0")/../Resources" && pwd)"
ATTENDRE="$RES/attendre.sh"
ICON="$RES/dialog-icon.png"
LIEN_DEFAUT="https://www.youtube.com/watch?v=8Mi1P8FLcH0&list=RD8Mi1P8FLcH0&start_radio=1"

mkdir -p "$CONFIG_DIR"
[[ -f "$CONFIG_LIEN" ]] || printf '%s' "$LIEN_DEFAUT" > "$CONFIG_LIEN"

# Écran d'accueil TB INFORMATIQUE (visible à chaque ouverture)
/usr/bin/osascript -e 'display dialog "© TB INFORMATIQUE" & return & "Thierry Bonsigne" & return & "Tél : 06-42-29-28-18" with title "Réveil musical — TB INFORMATIQUE" buttons {"Continuer"} default button "Continuer" with icon note' >/dev/null

while true; do
    LIEN=$(<"$CONFIG_LIEN")

    action=$($OSA - "$LIEN" <<'APPLESCRIPT'
on run argv
	set leLien to item 1 of argv
	set apercu to leLien
	if (length of apercu) > 50 then set apercu to (text 1 thru 50 of apercu) & "…"
	set etat to do shell script "if [ -f /tmp/reveil-musical.cible ]; then echo 'Réveil en attente pour : ' $(date -r $(cat /tmp/reveil-musical.cible) '+%H:%M le %d/%m'); else echo 'Aucun réveil réglé'; fi"
	set r to choose from list {"Régler le réveil", "Changer le lien", "Annuler le réveil", "Quitter"} with prompt "Réveil musical" & return & return & etat & return & return & "Lien actuel :" & return & apercu with title "Réveil musical — TB INFORMATIQUE"
	if r is false then return "Quitter"
	return item 1 of r
end run
APPLESCRIPT
    ) || exit 0

    case "$action" in
      "Changer le lien"|"Régler le réveil") ;;
      "Annuler le réveil")
          rm -f "$FICHIER_CIBLE"
          $OSA -e 'display notification "Réveil annulé." with title "Réveil musical — TB INFORMATIQUE"'
          continue ;;
      *)
          exit 0 ;;
    esac

    if [[ "$action" == "Changer le lien" ]]; then
        nouveau=$($OSA - "$LIEN" "$ICON" <<'APPLESCRIPT'
on run argv
	set r to display dialog "Nouveau lien (YouTube ou autre) :" default answer (item 1 of argv) buttons {"Annuler", "Enregistrer"} default button "Enregistrer" with title "Réveil musical — lien" with icon (POSIX file (item 2 of argv))
	return text returned of r
end run
APPLESCRIPT
        ) || continue
        printf '%s' "$nouveau" > "$CONFIG_LIEN"
        $OSA -e 'display notification "Lien enregistré." with title "Réveil musical — TB INFORMATIQUE"'
        continue
    fi

    # --- Régler le réveil ---
    heure=$($OSA - "$(date '+%H:%M')" "$ICON" <<'APPLESCRIPT'
on run argv
	set r to display dialog "Heure du réveil (format 24h) :" & return & return & "exemples : 07:00  ou  21:30" default answer (item 1 of argv) buttons {"Annuler", "OK"} default button "OK" with title "Réveil musical — heure" with icon (POSIX file (item 2 of argv))
	return text returned of r
end run
APPLESCRIPT
    ) || continue
    heure=$(printf '%02d:%02d' "${heure%%:*}" "${heure#*:}" 2>/dev/null) || continue
    if ! [[ "$heure" =~ ^[0-9][0-9]:[0-5][0-9]$ ]]; then continue; fi

    cible=$(date -j -f "%H:%M" "$heure" "+%s") || continue
    now=$(date +%s)
    quand=$(date -r "$cible" "+%H:%M le %d/%m")
    if (( cible <= now )); then
        cible=$((cible + 86400))
        quand=$(date -r "$cible" "+%H:%M le %d/%m (demain)")
    fi
    printf '%s' "$cible" > "$FICHIER_CIBLE"
    nohup bash "$ATTENDRE" "$cible" >/dev/null 2>&1 &

    veille=$($OSA - "$quand" "$ICON" <<'APPLESCRIPT'
on run argv
	set r to display dialog "Réveil réglé pour : " & (item 1 of argv) & return & return & "Le Mac doit être en veille (pas éteint) pour sonner." & return & "Voulez-vous aussi que le Mac se réveille tout seul à cette heure ? (nécessite le mot de passe)" buttons {"Non", "Oui"} default button "Non" with title "Réveil musical — TB INFORMATIQUE" with icon (POSIX file (item 2 of argv))
	return button returned of r
end run
APPLESCRIPT
    ) || veille="Non"
    if [[ "$veille" == "Oui" ]]; then
        wake=$(date -r "$cible" "+%m/%d/%Y %H:%M:%S")
        $OSA -e "do shell script \"/usr/bin/pmset schedule wake '$wake'\" with administrator privileges" \
            && $OSA -e 'display notification "Réveil matériel programmé." with title "Réveil musical — TB INFORMATIQUE"' \
            || $OSA -e "display dialog \"Impossible de programmer le réveil matériel (mot de passe refusé ?). Le réveil fonctionnera quand même si le Mac est en veille légère.\" buttons {\"OK\"} default button \"OK\" with title \"Réveil musical\" with icon file (POSIX file \"$ICON\")"
    fi
done
