#lang racket

(define memory (make-vector 1024 #\nul))

(define flag (if (getenv "FLAG") (getenv "FLAG") "NO-FLAG-DEFINED"))

(define (write-to-memory! str memory-start-index)
  (define str-length (string-length str))
  (define (loop str-index)
    (when (< str-index str-length)
        (vector-set! memory (+ memory-start-index str-index) (string-ref str str-index))
        (loop (+ str-index 1))))
  (loop 0))

(define (init-memory!)
  (write-to-memory! "admin\0" 8)
  (write-to-memory! (string-append flag "\0") 14))

(init-memory!)

(define (read-from-memory memory-start-index)
  (define (loop str curr-index)
    (if (equal? (vector-ref memory curr-index) #\nul)
      str
      (loop (string-append str (string (vector-ref memory curr-index))) (+ curr-index 1))))
  (loop "" memory-start-index))

(define (main)
  (display "Editing user name 'admin'\n")
  (display "Enter new name: ")
  (define new-username (symbol->string (read)))
  (if (> (string-length new-username) (- 14 8))
    (begin
        (display "Error: new username cannot be longer than old username\n")
        (main))
    (begin
      (write-to-memory! new-username 8)
      (display (string-append "Successfully changed username of 'admin' to '" (read-from-memory 8) "'")))))

(main)

