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

work=$(mktemp -d "$PIVILION_DIR/static.XXXXXX")
backup="$PIVILION_DIR/backups/gen-$(date +%Y%m%d-%H%M%S)"
trap 'rm -rf "$work"' EXIT
install -d -m 0755 -o "$PIVILION_USER" -g "$PIVILION_GROUP" "$PIVILION_DIR/backups"
cp -a "$PIVILION_WEBROOT/gen" "$backup"

wget --mirror --convert-links --adjust-extension --page-requisites \
    --restrict-file-names=ascii,windows http://127.0.0.1/ -P "$work"
[ -f "$work/127.0.0.1/index.html" ] || { echo "Static capture did not produce index.html; gallery was not changed." >&2; exit 1; }

find "$PIVILION_WEBROOT/gen" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} +
cp -a "$work/127.0.0.1/." "$PIVILION_WEBROOT/gen/"
mv "$PIVILION_WEBROOT/gen/index.html" "$PIVILION_WEBROOT/gen/index.php"
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 {} +

echo "Static gallery installed. Original backup: $backup"
select choice in "Hotspot" "Onion"; do
    case "$choice" in
        Hotspot)
            install -m 0644 -o root -g www-data "$PIVILION_DIR/config/html/.htaccess" "$PIVILION_WEBROOT/gen/.htaccess"
            break ;;
        Onion)
            rm -f "$PIVILION_WEBROOT/gen/.htaccess"
            break ;;
        *) echo "Choose 1 or 2." ;;
    esac
done
