#!/bin/bash

# --- 1. SYSTEM PREP & TOOL INSTALL ---
echo "--- Starting Medical Cybersecurity Master Setup ---"
sudo apt-get update -y
sudo apt-get install -y docker.io docker-compose-v2 nmap wireshark tcpdump dcmtk curl

# --- 2. PERMISSION REPAIR & SUDO SAFETY NET ---
echo "Configuring environment permissions..."
if ! getent group wireshark > /dev/null; then sudo groupadd wireshark; fi
sudo usermod -aG docker $USER
sudo usermod -aG wireshark $USER
sudo setcap 'CAP_NET_RAW+eip CAP_NET_ADMIN+eip' /usr/bin/dumpcap 2>/dev/null

# Add aliases to .bashrc for managed systems where groups don't stick
if ! grep -q "alias docker=" ~/.bashrc; then
    echo "alias docker='sudo docker'" >> ~/.bashrc
    echo "alias docker-compose='sudo docker-compose'" >> ~/.bashrc
    echo "alias fix-pms='newgrp docker && newgrp wireshark'" >> ~/.bashrc
fi

# --- 3. INFRASTRUCTURE WIPE (Ensures a clean start) ---
echo "Wiping old lab data..."
sudo docker rm -f orthanc_pacs 2>/dev/null
rm -rf ~/medical-lab
mkdir -p ~/medical-lab && cd ~/medical-lab

# --- 4. CONFIGURATION (The "No-Login" Fix) ---
cat <<EOF > orthanc.json
{
  "Name" : "Teaching_Hospital_PACS",
  "AuthenticationEnabled" : false,
  "RemoteAccessAllowed" : true,
  "DicomPort" : 4242,
  "HttpPort" : 8042
}
EOF

cat <<EOF > docker-compose.yml
services:
  pacs-server:
    image: jodogne/orthanc
    container_name: orthanc_pacs
    ports:
      - "4242:4242"
      - "8042:8042"
    volumes:
      - ./orthanc.json:/etc/orthanc/orthanc.json:ro
    command: /etc/orthanc/orthanc.json
    restart: unless-stopped
EOF

# --- 5. LAUNCH & DATA INJECTION ---
echo "Launching Vulnerable Hospital Server..."
sudo docker compose up -d

echo "Waiting 12 seconds for database to initialize..."
sleep 12

echo "Injecting Patient Records..."
for i in {1..5}; do
  case $i in
    1) name="DOE^JOHN^A" ;; 2) name="SMITH^JANE^B" ;; 3) name="BROWN^ROBERT^C" ;;
    4) name="DAVIS^MARIA^D" ;; 5) name="WILSON^JAMES^E" ;;
  esac
  curl -s -X POST http://127.0.0.1:8042/tools/create-dicom \
       -d "{\"PatientName\":\"$name\",\"PatientID\":\"VA-ID-00$i\",\"Modality\":\"OT\"}" > /dev/null
done

echo "Injecting Secret Flag Patient..."
curl -s -X POST http://127.0.0.1:8042/tools/create-dicom \
     -d "{
        \"PatientName\":\"FLAG^HIDDEN^REDACTED\",
        \"PatientID\":\"SECRET-999\",
        \"PatientComments\":\"CTF{MED_DATA_LEAK_2026}\",
        \"Modality\":\"OT\"
     }" > /dev/null

# --- 6. FINAL VERIFICATION ---
COUNT=$(curl -s http://127.0.0.1:8042/patients | grep -o '".*"' | wc -l)

echo "--------------------------------------------------"
echo "SETUP COMPLETE!"
echo "Hospital is LIVE at http://localhost:8042"
echo "Patient Count: $COUNT (Expected: 6)"
echo "--------------------------------------------------"
echo "STUDENTS: If 'docker ps' fails, type: source ~/.bashrc"
echo "--------------------------------------------------"

source ~/.bashrc
# Refresh current shell session
exec sg docker -c "newgrp wireshark -c 'exec bash'"