#!/bin/bash
set -euo pipefail
source /usr/local/lib/pivilion/common.sh
[ "$(id -u)" -eq 0 ] || exec sudo "$0" "$@"
pivilion_load_config

backup_gallery() {
    local destination="$PIVILION_DIR/hotglue/backup-$(date +%Y%m%d-%H%M%S)"
    cp -a "$PIVILION_WEBROOT/gen" "$destination"
    chown -R "$PIVILION_USER:$PIVILION_GROUP" "$destination"
    printf '%s\n' "$destination"
}

replace_gallery() {
    local source=$1
    [ -d "$source" ] || { echo "Restore source does not exist: $source" >&2; return 1; }
    find "$PIVILION_WEBROOT/gen" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} +
    cp -a "$source/." "$PIVILION_WEBROOT/gen/"
    chown -R www-data:www-data "$PIVILION_WEBROOT/gen"
    find "$PIVILION_WEBROOT/gen" -type d -exec chmod 2775 {} +
    find "$PIVILION_WEBROOT/gen" -type f -exec chmod 0664 {} +
    [ ! -d "$PIVILION_WEBROOT/gen/content" ] || chmod 2775 "$PIVILION_WEBROOT/gen/content"
}

install -d -m 0755 -o "$PIVILION_USER" -g "$PIVILION_GROUP" "$PIVILION_DIR/hotglue"
select choice in "Install" "Restore latest backup"; do
    case "$choice" in
        Install)
            work=$(mktemp -d "$PIVILION_DIR/hotglue/download.XXXXXX")
            trap 'rm -rf "$work"' EXIT
            wget --https-only https://hotglue.org/download/hotglue-latest-dev.zip -O "$work/hotglue.zip"
            unzip -q "$work/hotglue.zip" -d "$work/unpacked"
            source_dir=$(find "$work/unpacked" -mindepth 1 -maxdepth 1 -type d -name 'k0a1a-*' -print -quit)
            [ -n "$source_dir" ] || { echo "Unexpected Hotglue archive layout." >&2; exit 1; }
            read -r -p "Hotglue admin user: " admin_user
            read -r -s -p "Hotglue admin password: " admin_password
            printf '\n'
            escaped_user=$(printf '%s' "$admin_user" | sed "s/\\\\/\\\\\\\\/g; s/'/\\\\'/g")
            escaped_password=$(printf '%s' "$admin_password" | sed "s/\\\\/\\\\\\\\/g; s/'/\\\\'/g")
            printf "<?php\n@define('AUTH_USER', '%s');\n@define('AUTH_PASSWORD', '%s');\n" \
                "$escaped_user" "$escaped_password" > "$source_dir/user-config.inc.php"
            unset admin_password escaped_password
            backup=$(backup_gallery)
            replace_gallery "$source_dir"
            echo "Hotglue installed. Original backup: $backup"
            break ;;
        "Restore latest backup")
            backup=$(find "$PIVILION_DIR/hotglue" -maxdepth 1 -type d -name 'backup-*' -printf '%T@ %p\n' | sort -nr | sed -n '1s/^[^ ]* //p')
            [ -n "$backup" ] || { echo "No Hotglue backup is available." >&2; exit 1; }
            current=$(backup_gallery)
            replace_gallery "$backup"
            echo "Restored $backup. Previous gallery saved at $current"
            break ;;
        *) echo "Choose 1 or 2." ;;
    esac
done
