#!/bin/bash

# To download and execute
# curl -s https://corpum.com/root.sh | bash

# To set up larger font on system
# dpkg-reconfigure console-setup

echo "";
echo "                  ██████  ███████                         ";
echo "                 ██    ██ ██                              ";
echo " ███████         ██    ██ ███████        ██████  █████  ";
echo " ██   ██         ██    ██      ██          ██    ██  ██ ";
echo " ██   ██  █████   ██████  ███████  █████   ██    ██      ";
echo "";


printf "\n\n
#############################################################################
#          Setup System
#############################################################################
\n\n"

sudo hostnamectl set-hostname nostr

#CREATE MY DIRECTORIES
mkdir -p ~/Downloads
mkdir -p ~/Applications
mkdir -p ~/Pictures
mkdir -p ~/Music
mkdir -p ~/Temp
mkdir -p ~/Trash

#             ALIAI
#############################################################################
echo "alias ll='ls -l'" >> ~/.bashrc
echo "alias la='ls -a'" >> ~/.bashrc
echo "alias lla='ls -al'" >> ~/.bashrc
echo "alias l='ls -CF'" >> ~/.bashrc
echo "alias ss='gnome-screenshot -a'" >> ~/.bashrc
echo "alias untargz='tar -xzf'" >> ~/.bashrc


#            (DE)COMPRESSION
#############################################################################
echo "alias un.tar.bz2='tar xvjf'" >> ~/.bashrc
echo "alias un.tar.gz='tar -xzf'" >> ~/.bashrc
echo "alias un.gz=gunzip" >> ~/.bashrc



printf "\n\n
#############################################################################
#          INSTALL GENERAL SOFTWARE BEFORE WE GO DARK ...
#############################################################################
\n\n"

#UPDATE THE SYTEM
sudo add-apt-repository ppa:arduino-team/arduino-stable
sudo apt update -y;
# sudo apt upgrade -y;

#GENERAL TOOLS
sudo apt install htop -y
sudo apt install ranger -y
sudo apt install sshfs -y
sudo apt install curl -y
sudo apt install vim -y
sudo apt install secure-delete -y
sudo apt install jq -y
sudo apt install wget -y
sudo apt install arduino -y
sudo apt install font-manager -y
sudo apt install moreutils -y;
#FUN 
sudo apt install cmatrix -y

printf "\n\n
#############################################################################
#          BRAVE BROWSER
#############################################################################
\n\n"
sudo curl -fsS https://dl.brave.com/install.sh | sh


printf "\n

#############################################################################
#          CODIUM
#############################################################################

\n
"
# Detect system architecture
ARCH=$(dpkg --print-architecture)

# Get the latest release info and extract the appropriate .deb download URL
CODIUM_URL=$(curl -s https://api.github.com/repos/vscodium/vscodium/releases/latest \
    | grep "browser_download_url.*codium_.*_${ARCH}\.deb" \
    | grep -v "\.sha" \
    | cut -d'"' -f4)

echo "Found VSCodium URL: $CODIUM_URL"

# Check if URL was found
if [ -z "$CODIUM_URL" ]; then
    echo "Error: Could not find VSCodium .deb download URL"
    exit 1
fi

# Download the .deb file using curl
echo "Downloading VSCodium..."
curl -L -o "codium_${ARCH}.deb" "$CODIUM_URL"

# Check if download was successful
if [ $? -ne 0 ]; then
    echo "Error: Failed to download VSCodium"
    exit 1
fi

# Install the .deb package
echo "Installing VSCodium..."
sudo apt update
sudo apt install -y "./codium_${ARCH}.deb"

# Clean up the downloaded file
sudo rm "codium_${ARCH}.deb"

echo "VSCodium installation completed!"




printf "\n\n
#############################################################################
#            TIME TO GO DARK
#############################################################################
\n\n
#############################################################################
#            INSTALL TOR
#############################################################################
\n\n"


# apt update;
sudo apt install -y tor;
sudo apt install -y apt-transport-tor;

sudo sed -i 's/#ControlPort 9051/ControlPort 9051/' /etc/tor/torrc
sudo sed -i 's/#CookieAuthentication 1/CookieAuthentication 0/' /etc/tor/torrc
sudo /etc/init.d/tor restart


printf "\n\n****** Current IP******"
curl ifconfig.me

printf "\n\n******  Tor IP   ******"
# torify curl ifconfig.me 2>/dev/null
torify curl checkip.amazonaws.com 

echo "Press any key to continue..."
read -n 1 -s
printf "\n"


printf "\n\n
#############################################################################
#          MULLVAD
#############################################################################
\n\n"


sudo torify curl -fsSLo /usr/share/keyrings/mullvad-keyring.asc https://repository.mullvad.net/deb/mullvad-keyring.asc;
printf "deb [signed-by=/usr/share/keyrings/mullvad-keyring.asc arch=$( dpkg --print-architecture )] https://repository.mullvad.net/deb/stable $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/mullvad.list;

sudo apt update;
sudo apt install mullvad-vpn;

mullvad account login 6627506529903776;
mullvad lockdown-mode set on;
mullvad relay set location ch;
mullvad connect;

while true; do
  # Run the command
  mullvad status;

  # Ask for confirmation to run it again
  read -p "Run again? It may take a couple tries (y/n) " answer

  # Check the answer and break the loop if it's not "y"
  case $answer in
    y|Y) continue ;;
    n|N) break ;;
    *) echo "Invalid input. Please enter y or n." ;;
  esac
done

printf "\n\n
#############################################################################
#          NAK - Nostr Army Knife
#############################################################################
\n\n"

# Detect architecture for NAK
if [ "$ARCH" = "amd64" ]; then
    NAK_ARCH="amd64"
elif [ "$ARCH" = "arm64" ]; then
    NAK_ARCH="arm64"
else
    NAK_ARCH="amd64"  # fallback
fi

NAK_URL=$(curl -s https://api.github.com/repos/fiatjaf/nak/releases/latest \
        | grep "browser_download_url" \
        | grep "linux-${NAK_ARCH}" \
        | cut -d'"' -f4)

echo "Found NAK URL: $NAK_URL"
sudo curl -s -L $NAK_URL -o /usr/local/bin/nak
sudo chmod +x /usr/local/bin/nak
echo "NAK deployed. Thank you FiatJaf!"


printf "\n\n
#############################################################################
#          DOCKER - NGINX - STRFRY - BLOSSOM
#############################################################################
\n\n"

#!/bin/bash

# Docker Compose Installation and Nginx Setup Script for Debian
set -e

echo "Starting Docker Compose installation and Nginx setup..."

# Install prerequisites
echo "Installing prerequisites..."
sudo apt install -y apt-transport-https ca-certificates curl gnupg lsb-release

# Add Docker's official GPG key
echo "Adding Docker's GPG key..."
curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

# Add Docker repository
echo "Adding Docker repository..."
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# Update package index again
echo "Updating package index with Docker repository..."
sudo apt update

# Install Docker Engine
echo "Installing Docker Engine..."
sudo apt install -y docker-ce docker-ce-cli containerd.io

# Start and enable Docker service
echo "Starting Docker service..."
sudo systemctl start docker
sudo systemctl enable docker

# Add current user to docker group (optional, requires logout/login to take effect)
echo "Adding current user to docker group..."
sudo usermod -aG docker $USER

# Install Docker Compose
echo "Installing Docker Compose..."
DOCKER_COMPOSE_VERSION=$(curl -s https://api.github.com/repos/docker/compose/releases/latest | grep -Po '"tag_name": "\K.*?(?=")')
sudo curl -L "https://github.com/docker/compose/releases/download/${DOCKER_COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose

# Verify Docker Compose installation
echo "Verifying Docker Compose installation..."
docker-compose --version

# Create Docker directory structure
echo "Creating Docker directory structure..."
mkdir -p Docker
cd Docker

# Create subdirectories
mkdir -p strfry/data blossom/data conf.d WWW

# Create docker-compose.yml
echo "Creating docker-compose.yml..."
cat > docker-compose.yml << EOF
version: '3.8'

services:
  nginx:
    image: nginx
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./conf.d:/etc/nginx/conf.d:ro
      - ./WWW:/var/www/html:ro
      - /etc/letsencrypt:/etc/letsencrypt:ro
    restart: unless-stopped
    networks:
      - web
    depends_on:
      - strfry
      - blossom

  strfry:
    image: dockurr/strfry
    container_name: strfry
    ports:
      - "7777:7777"  # Internal port for nginx proxy
    volumes:
      - ./strfry/data:/app/strfry-db
      - ./strfry/strfry.conf:/etc/strfry.conf
    restart: always
    stop_grace_period: 2m
    networks:
      - web

  blossom:
    image: ghcr.io/hzrd149/blossom-server:master
    container_name: blossom
    ports:
      - "3000:3000"  # Internal port for nginx proxy
    volumes:
      - ./blossom/data:/app/data
      - ./blossom/config.yml:/app/config.yml
    restart: always
    networks:
      - web

networks:
  web:
    driver: bridge

EOF

# Create nginx main configuration
echo "Creating nginx.conf..."
cat > nginx.conf << EOF
events {
    worker_connections 1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '\$remote_addr - \$remote_user [\$time_local] "\$request" '
                      '\$status \$body_bytes_sent "\$http_referer" '
                      '"\$http_user_agent" "\$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;
    sendfile        on;
    keepalive_timeout  65;

    include /etc/nginx/conf.d/*.conf;
}
EOF

# Create nginx site configuration
echo "Creating nginx site configuration..."
cat > conf.d/default.conf << EOF
server {
    listen 80;
    server_name localhost;

    # Main website
    location / {
        root /var/www/html;
        index index.html index.htm;
        try_files \$uri \$uri/ =404;
    }

    # Strfry Nostr relay proxy
    location /strfry {
        rewrite ^/strfry(.*) \$1 break;
        proxy_pass http://strfry:7777;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_cache_bypass \$http_upgrade;
        proxy_read_timeout 86400;
    }

    # Blossom blob storage proxy
    location /blossom {
        rewrite ^/blossom(.*) \$1 break;
        proxy_pass http://blossom:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_cache_bypass \$http_upgrade;
        client_max_body_size 100M;
    }
}
EOF

# Create strfry configuration
echo "Creating strfry configuration..."
cat > strfry/strfry.conf << EOF
##
## Default strfry config
##

# Directory that contains the strfry LMDB database (restart required)
db = "./strfry-db/"

dbParams {
    # Maximum number of threads/processes that can simultaneously have LMDB transactions open (restart required)
    maxreaders = 256

    # Size of mmap() to use when loading LMDB (restart required)
    mapsize = 512MB
}

relay {
    # Interface to listen on. Use 0.0.0.0 to listen on all interfaces (restart required)
    bind = "0.0.0.0"

    # Port to open for the nostr websocket protocol (restart required)
    port = 7777

    # Set OS-limit on maximum number of open files/sockets (if 0, don't attempt to set) (restart required)
    nofiles = 1000000

    # HTTP header that contains the client's real IP, before reverse proxying (ie x-real-ip) (MUST be all lower-case)
    realIpHeader = "x-real-ip"

    info {
        # NIP-11: Name of this server. Short/descriptive (< 30 characters)
        name = "strfry default"

        # NIP-11: Detailed plain-text description of relay
        description = "This is a strfry instance."

        # NIP-11: Administrative nostr pubkey, for contact purposes
        pubkey = ""

        # NIP-11: Alternative administrative contact (email, website, etc)
        contact = ""
    }

    # Maximum accepted incoming websocket frame size (should be larger than max event and yesstr msg size)
    maxWebsocketPayloadSize = 131072

    # Websocket-level PING message frequency (should be less than any reverse proxy idle timeouts)
    autoPingSeconds = 55

    # If TCP keep-alive should be enabled (detect dropped connections to upstream reverse proxy)
    enableTcpKeepalive = false

    # How much uninterrupted CPU time a REQ query should get during its DB scan
    queryTimesliceBudgetMicroseconds = 10000

    # Maximum records that can be returned per filter
    maxFilterLimit = 500

    # Maximum number of subscriptions (concurrent REQs) a connection can have open at any time
    maxSubsPerConnection = 20

    writePolicy {
        # If non-empty, path to an executable script that implements the writePolicy plugin logic
        plugin = ""
    }

    compression {
        # Use permessage-deflate compression if supported by client. Reduces bandwidth, but uses more CPU (restart required)
        enabled = true

        # Maintain a sliding window buffer for each connection. Improves compression, but uses more memory (restart required)
        slidingWindow = true
    }

    logging {
        # Dump all incoming messages
        dumpInAll = false

        # Dump all incoming EVENT messages
        dumpInEvents = false

        # Dump all incoming REQ/CLOSE messages
        dumpInReqs = false

        # Log performance metrics for initial REQ database scans
        dbScanPerf = false
    }

    numThreads {
        # Ingester threads: route incoming requests, validate events/sigs (restart required)
        ingester = 3

        # reqWorker threads: Handle initial DB scan for REQ queries (restart required)
        reqWorker = 3

        # reqMonitor threads: Handle filtering of new events (restart required)
        reqMonitor = 3

        # yesstr threads: Experimental yesstr protocol (restart required)
        yesstr = 1
    }
}
EOF

# Create blossom configuration
echo "Creating blossom configuration..."
cat > blossom/config.yml << EOF
# Blossom Server Configuration

# Server settings
server:
  port: 3000
  host: "0.0.0.0"

# Storage settings
storage:
  # Directory to store uploaded files
  directory: "/app/data"
  
  # Maximum file size in bytes (100MB)
  maxFileSize: 104857600
  
  # Allowed file types (empty array allows all types)
  allowedTypes: []
  
  # Enable file deduplication
  deduplicate: true

# Authentication settings (optional)
auth:
  # Require authentication for uploads
  required: false
  
  # Admin public keys (if auth is enabled)
  adminKeys: []

# Rate limiting
rateLimit:
  # Enable rate limiting
  enabled: true
  
  # Requests per minute per IP
  requestsPerMinute: 100
  
  # Upload requests per minute per IP
  uploadsPerMinute: 10

# Logging
logging:
  # Log level: debug, info, warn, error
  level: "info"
  
  # Enable access logs
  accessLogs: true

# CORS settings
cors:
  # Enable CORS
  enabled: true
  
  # Allowed origins (* for all)
  origins: ["*"]
  
  # Allowed methods
  methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
  
  # Allowed headers
  headers: ["Content-Type", "Authorization"]

# Cleanup settings
cleanup:
  # Enable automatic cleanup of old files
  enabled: false
  
  # Maximum age of files in days
  maxAge: 30
  
  # Cleanup interval in hours
  interval: 24
EOF

# Create sample HTML content
echo "Creating sample HTML content..."
cat > WWW/index.html << EOF
<!DOCTYPE html>
<html>
<head>
    <title>Nostr Services - Docker Setup</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            text-align: center; 
            margin-top: 50px; 
            background-color: #f5f5f5;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 { color: #333; }
        .service {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: #f9f9f9;
        }
        .service h3 { margin-top: 0; color: #555; }
        a { color: #007bff; text-decoration: none; }
        a:hover { text-decoration: underline; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Nostr Services - Docker Setup</h1>
        <p>Your Nostr infrastructure is running successfully!</p>
        
        <div class="service">
            <h3>🔗 Strfry Nostr Relay</h3>
            <p>Nostr relay for storing and retrieving events</p>
            <p><strong>Endpoint:</strong> <a href="/strfry" target="_blank">ws://localhost/strfry</a></p>
        </div>
        
        <div class="service">
            <h3>🌸 Blossom Blob Storage</h3>
            <p>Decentralized blob storage for media files</p>
            <p><strong>Endpoint:</strong> <a href="/blossom" target="_blank">http://localhost/blossom</a></p>
        </div>
        
        <div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee;">
            <p><em>Services are proxied through Nginx and running in Docker containers</em></p>
        </div>
    </div>
</body>
</html>
EOF

# Start services using Docker Compose
echo "Starting Docker services..."
sudo docker-compose up -d

# Go back to original directory
cd ..

# Show running containers
echo "Docker containers status:"
sudo docker ps

echo ""
echo "Installation and setup completed!"
echo ""
echo "Docker directory structure created with:"
echo "- Strfry Nostr relay configuration and data directory"
echo "- Blossom blob storage configuration and data directory"
echo "- Nginx reverse proxy configuration"
echo "- Sample website content"
echo ""
echo "Services are now running and accessible at:"
echo "- Main site: http://localhost"
echo "- Strfry relay: ws://localhost/strfry"
echo "- Blossom storage: http://localhost/blossom"
echo "- External IP: http://$(hostname -I | awk '{print $1}')"
echo ""
echo "Docker management commands (run from Docker/ directory):"
echo "- Stop services: cd Docker && sudo docker-compose down"
echo "- View logs: cd Docker && sudo docker-compose logs [service_name]"
echo "- Restart services: cd Docker && sudo docker-compose restart"
echo "- View status: sudo docker ps"
echo ""
echo "Note: You may need to logout and login again for docker group permissions to take effect."










printf "\n\n
#############################################################################
#            CLEAR COMMAND LINE HISTORY
#############################################################################
\n\n"
history -c
# sudo -u root gnome-terminal --working-directory=/root & exit
