#!/bin/bash

set -e

export DOMAIN_NAME="live.fic.srs.epita.fr"
export IP_FRONTEND="10.42.192.3/24"
export IP_FRONTEND_ROUTER="10.42.192.1"
export IP_FIC_SRS_FR=$(host ${DOMAIN_NAME} | grep -o '\([0-9]\{1,3\}.\)\+')
export IPS_BACKEND="192.168.3.92/24\\n192.168.4.92/24\\n"
export IP_BACKEND_ROUTER="192.168.3.1"

export AIRBUS_DESTINATION="gaming.cyberrange.lan"
export AIRBUS_BASEURL="https://${AIRBUS_DESTINATION}/api"
export AIRBUS_TOKEN="abcdef0123456789abcdef0123456789"
export AIRBUS_SESSION_NAME="Forensique"

export IPS_FRONTEND="${IP_FRONTEND}\\n${IP_FIC_SRS_FR}\\n"

escape_newline () {
    sed 's/$/\\n/g' | tr -d '\n'
}

if [ $# -gt 0 ]
then
    which jq > /dev/null 2> /dev/null || { echo "Please install jq" >&2; exit 1; }

    # Expect a previous ISO to update:
    # Keep: DM_CRYPT, DHPARAMs and SYNCHRO_SSH_KEY

    P=$(pwd)
    D=$(mktemp -d)
    pushd "${D}" > /dev/null

    isoinfo -i "${P}/$1" -X -find -iname "USER_DAT*" > /dev/null || 7z x "$1" > /dev/null

    FNAME="USER_DAT.;1"
    if ! [ -f "$FNAME" ] && [ -f user-data ]
    then
        FNAME="user-data"
    fi

    export DM_CRYPT=$(jq -r '."dm-crypt".entries.key.content' "${FNAME}" | tr -d '\n')
    export DHPARAM=$(jq -r '."tls_config".entries."dhparams-4096.pem".content' "${FNAME}" | escape_newline)
    export SYNCRO_PRIVATE_KEY=$(jq -r '.synchro.entries.id_ed25519.content' "${FNAME}" | escape_newline)
    export SYNCRO_PUBLIC_KEY=$(jq -r '.synchro.entries."id_ed25519.pub".content' "${FNAME}" | escape_newline)

    popd > /dev/null
    rm -rf "${D}"
fi

which vault > /dev/null 2> /dev/null || { echo "Please install vault" >&2; exit 1; }

export VAULT_ADDR="${VAULT_ADDR:-"https://vault.srs.epita.fr:443"}"
SSH_PATH="${SSH_PATH:-/tmp/fic_ssh}"
DHPARAM_PATH="${DHPARAM_PATH:-/tmp/dhparam.pem}"
OUTPUT_PATH="${OUTPUT_PATH:-"$(mktemp -d)"}"

command -v vault &> /dev/null || (echo "vault could not be found" && exit)
vault login -method=oidc -no-print 2> /dev/null

[ -z "${DM_CRYPT}" ] && echo "/!\\ GENERATE NEW DM_CRYPT SECRETS" && export DM_CRYPT="$(tr -d -c "a-zA-Z0-9" < /dev/urandom | fold -w512 | head -n 1)"
export CERT_PEM="$(vault kv get --field=cert.pem fic/cert/${DOMAIN_NAME} | escape_newline)"
export CHAIN_PEM="$(vault kv get --field=chain.pem fic/cert/${DOMAIN_NAME} | escape_newline)"
export FULLCHAIN_PEM="$(vault kv get --field=fullchain.pem fic/cert/${DOMAIN_NAME} | escape_newline)"
export PRIVKEY_PEM="$(vault kv get --field=privkey.pem fic/cert/${DOMAIN_NAME} | escape_newline)"

if [ -z "${SYNCRO_PUBLIC_KEY}" ] || [ -z "${SYNCRO_PRIVATE_KEY}" ]
then
    ssh-keygen -a 100 -t ed25519 -q -f "$SSH_PATH" -N "" <<< 'y'

    export SYNCRO_PUBLIC_KEY="$(cat "$SSH_PATH".pub | escape_newline)"
    export SYNCRO_PRIVATE_KEY="$(cat "$SSH_PATH" | escape_newline)"
fi

if [ -z "${DHPARAM}" ] && ! [ -f "$DHPARAM_PATH" ]
then
    command -v openssl &> /dev/null || (echo "openssl could not be found" && exit)

    echo -e "\n\nGenerating DH params please wait"
    openssl dhparam -out "$DHPARAM_PATH" 4096 &>/dev/null
elif ! [ -f "$DHPARAM_PATH" ]
then
    echo "${DHPARAM}" > "${DHPARAM_PATH}"
fi
export DHPARAM="$(cat "$DHPARAM_PATH" | escape_newline)"

export AUTHORIZED_KEYS="$(cat "$(dirname $0)/authorized_keys" | escape_newline)"

TEMPLATE='
{
  "dm-crypt": {
    "entries": {
      "key": {
        "perm": "0440",
        "content": "${DM_CRYPT}"
      }
    }
  },
  "ssh": {
    "entries": {
      "authorized_keys": {
        "perm": "0444",
        "content": "${AUTHORIZED_KEYS}"
      }
    }
  },
  "synchro": {
    "entries": {
      "id_ed25519": {
        "perm": "0400",
        "content": "${SYNCRO_PRIVATE_KEY}"
      },
      "id_ed25519.pub": {
        "perm": "0444",
        "content": "${SYNCRO_PUBLIC_KEY}"
      }
    }
  },
  "ip_config": {
    "entries": {
      "frontend-players": {
        "perm": "0444",
        "content": "${IPS_FRONTEND}"
      },
      "frontend-router": {
        "perm": "0444",
        "content": "${IP_FRONTEND_ROUTER}"
      },
      "backend-admin": {
        "perm": "0444",
        "content": "${IPS_BACKEND}"
      },
      "backend-router": {
        "perm": "0444",
        "content": "${IP_BACKEND_ROUTER}"
      },
      "domain": {
        "perm": "0444",
        "content": "${DOMAIN_NAME}"
      }
    }
  },
  "remote_sync": {
    "entries": {
      "baseurl": {
        "perm": "0444",
        "content": "${AIRBUS_BASEURL}"
      },
      "destination": {
        "perm": "0444",
        "content": "${AIRBUS_DESTINATION}"
      },
      "token": {
        "perm": "0444",
        "content": "${AIRBUS_TOKEN}"
      },
      "session_name": {
        "perm": "0444",
        "content": "${AIRBUS_SESSION_NAME}"
      }
    }
  },
  "tls_config": {
    "entries": {
      "dhparams-4096.pem": {
        "perm": "0400",
        "content": "${DHPARAM}"
      },
      "cert.pem": {
        "perm": "0400",
        "content": "${CERT_PEM}"
      },
      "chain.pem": {
        "perm": "0400",
        "content": "${CHAIN_PEM}"
      },
      "fullchain.pem": {
        "perm": "0400",
        "content": "${FULLCHAIN_PEM}"
      },
      "privkey.pem": {
        "perm": "0444",
        "content": "${PRIVKEY_PEM}"
      }
    }
  }
}'

echo "$TEMPLATE" | envsubst > "$OUTPUT_PATH"/user-data

echo -e "Result in $OUTPUT_PATH\nGenerating iso"

mkisofs -joliet-long -V CIDATA -o fickit-metadata.iso "${OUTPUT_PATH}"
