#!/bin/bash

set -e

read -r -p "Issuer: " ISSUER
read -r -p "Service (e.g. QFIXPT): " SERVICE
read -r -p "Token: " TOKEN
read -r -p "Expire (e.g. 24h) [none]: " EXPIRY

if [ -z "$EXPIRY" ]; then
    EXPIRY="none"
fi

# Check if secret key is set
SERVICE_UPPER=$(printf "%s" "$SERVICE" | tr '[:lower:]' '[:upper:]')
SECRET_KEY_VAR="${SERVICE_UPPER}_QUANTEX_SECRET_KEY"
if [ -z "${!SECRET_KEY_VAR}" ]; then
    echo "Error: Environment variable $SECRET_KEY_VAR is not set" >&2
    echo "" >&2
    echo "Please set the secret key:" >&2
    echo "  export $SECRET_KEY_VAR=\"your-secret-key\"" >&2
    exit 1
fi

# Create temporary directory
TEMP_DIR=$(mktemp -d)
trap "rm -rf $TEMP_DIR" EXIT

# Create Go program
cat > "$TEMP_DIR/main.go" << 'GOCODE'
package main

import (
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/golang-jwt/jwt"
)

func main() {
	if len(os.Args) != 5 {
		fmt.Fprintf(os.Stderr, "Usage: %s <token> <issuer> <expiry> <secret>\n", os.Args[0])
		os.Exit(1)
	}

	token := os.Args[1]
	issuer := os.Args[2]
	expiryStr := os.Args[3]
	secret := os.Args[4]

	now := time.Now()
	claims := jwt.MapClaims{
		"token":       token,
		"permissions": []string{"FullAccess"},
		"iss":         issuer,
		"iat":         now.Unix(),
	}

	if strings.ToLower(expiryStr) != "none" && expiryStr != "-1" {
		duration, err := time.ParseDuration(expiryStr)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error: Invalid expiry duration '%s': %v\n", expiryStr, err)
			fmt.Fprintf(os.Stderr, "Use format like: 1h, 24h, 7d, 168h\n")
			os.Exit(1)
		}
		claims["exp"] = now.Add(duration).Unix()
	}

	// Create token
	jwttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	// Sign token
	signedToken, err := jwttoken.SignedString([]byte(secret))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: Failed to sign token: %v\n", err)
		os.Exit(1)
	}

	// Output token
	fmt.Println(signedToken)
}
GOCODE

# Initialize go.mod in temp directory
cd "$TEMP_DIR"
cat > go.mod << GOMOD
module jwt-generator

go 1.24

require github.com/golang-jwt/jwt v3.2.2+incompatible
GOMOD

go mod download > /dev/null 2>&1

# Build the Go program
go build -o jwt-gen main.go 2>&1 | grep -v "go: downloading" || true

# Run the Go program
JWT_TOKEN=$(./jwt-gen "$TOKEN" "$ISSUER" "$EXPIRY" "${!SECRET_KEY_VAR}")

if [ $? -ne 0 ]; then
    echo "Error: Failed to generate JWT token" >&2
    exit 1
fi

# Output the token
echo "$JWT_TOKEN"
