#!/usr/bin/python

# Use this file to add SCION AS entries to the whois database

import os
import json

# Function to convert SCION AS to decimal if in BGP range
def scion_as_to_decimal(as_id):
    """Convert SCION AS format to decimal if in BGP AS range (0 - 2^32-1)"""
    # Handle plain decimal AS numbers
    if ':' not in as_id:
        return as_id
    
    # Parse SCION format
    parts = as_id.split(':')
    
    # Check if this looks like ISD:AS:Instance format (first part is single digit ISD)
    if len(parts) == 3 and len(parts[0]) == 1 and parts[0].isdigit():
        # ISD:AS:Instance format - convert the AS part (middle) and instance (last)
        try:
            # AS is 16-bit hex, instance is 16-bit hex
            # Combine them as 32-bit number: AS << 16 | Instance
            as_num = int(parts[1], 16)
            instance = int(parts[2], 16)
            total = (as_num << 16) | instance
            
            if 0 <= total <= 0xFFFFFFFF:  # BGP AS range
                return str(total)
        except ValueError:
            pass
        return ""
    
    # For standard colon-separated hex format (e.g., 0:1:f)
    # Each part is up to 16 bits
    try:
        total = 0
        for part in parts:
            total = (total << 16) + int(part, 16)
        
        # Check if in BGP AS range
        if 0 <= total <= 0xFFFFFFFF:  # 2^32 - 1
            return str(total)
    except ValueError:
        pass
    
    return ""

# Ensure the AS database directory exists
os.system("mkdir -p db/as")

as_id = input("Enter SCION AS Identifier (format ISD:AS:Instance, e.g. 2:2:0): ")

# Validate AS ID format
import re
if not re.match(r'^\d+:\d+:\d+$', as_id) and not re.match(r'^\d+$', as_id):
    print("Invalid SCION AS Identifier format. Expected format: ISD:AS:Instance (e.g. 2:2:0) or just AS number (e.g. 60284)")
    exit(1)

# Get AS details
isd = input("Enter ISD: ")
# Automatically calculate decimal representation
as_decimal = scion_as_to_decimal(as_id)
if as_decimal:
    print(f"AS decimal value (auto-calculated): {as_decimal}")
else:
    as_decimal = input("Enter AS decimal value (not in BGP range, press Enter to skip): ")
    
organization = input("Enter Organization: ")
country = input("Enter Country Code: ")
uid = input("Enter UID (e.g. CHE-123.456.789): ")
status = input("Enter Status (ASSIGNED/ALLOCATED): ")
description = input("Enter Description: ")
contact = input("Enter Contact Email: ")
date_allocated = input("Enter Date Allocated (YYYY-MM-DD): ")

# Prepare AS data
n = "\r\n"
body = "% SCION AS WHOIS Information" + n + n
body += "AS Identifier:  " + as_id + n
body += "ISD:           " + isd + n
body += "AS decimal:    " + as_decimal + n
body += "Organization:  " + organization + n
body += "Country:       " + country + n
body += "UID:           " + uid + n
body += "Status:        " + status + n
body += "Description:   " + description + n
body += "Contact:       " + contact + n
body += "DateAllocated: " + date_allocated + n

# Save to file
d = open("db/as/" + as_id, "w+")
d.write(body)
d.close()
print("Done! SCION AS record added successfully.")
