#!/bin/bash
# Skript för att fixa filrättigheter för shorten-servicen på Synology NAS
# Kör detta via SSH på din NAS

echo "Fixing permissions for URL Shortener service..."

# Navigera till projektkatalogen
cd /volume1/web/securitate/shorten || exit 1

# Sätt rätt behörigheter för katalogen
echo "Setting directory permissions..."
chmod 755 .

# Sätt behörigheter för JSON-filen
if [ -f shortenedurls.json ]; then
    echo "Setting file permissions for shortenedurls.json..."
    chmod 664 shortenedurls.json
else
    echo "Creating shortenedurls.json..."
    echo '{}' > shortenedurls.json
    chmod 664 shortenedurls.json
fi

# Försök identifiera webbserver-gruppen
# Synology använder vanligtvis 'http' eller 'www-data'
HTTP_GROUP="http"
if ! getent group "$HTTP_GROUP" > /dev/null 2>&1; then
    HTTP_GROUP="www-data"
    if ! getent group "$HTTP_GROUP" > /dev/null 2>&1; then
        echo "Warning: Could not find http or www-data group"
        echo "You may need to manually set the group"
        HTTP_GROUP=""
    fi
fi

# Sätt rätt grupp om vi hittade en
if [ -n "$HTTP_GROUP" ]; then
    echo "Setting group to $HTTP_GROUP..."
    chgrp "$HTTP_GROUP" .
    if [ -f shortenedurls.json ]; then
        chgrp "$HTTP_GROUP" shortenedurls.json
    fi
fi

# Visa resultat
echo ""
echo "Current permissions:"
ls -la | grep -E "(^d|shortenedurls.json)"

echo ""
echo "Testing write access..."
if [ -w shortenedurls.json ]; then
    echo "✓ File is writable!"
else
    echo "✗ File is still not writable"
    echo ""
    echo "Try running as root or with sudo:"
    echo "  sudo bash fix_permissions.sh"
fi

