#!/bin/bash

source /usr/lib/vault-bootstrap/lib/common.sh \
    || { echo "FATAL: Could not read /usr/lib/vault-bootstrap/lib/common.sh" >&2; exit 1; }

# shellcheck disable=SC2154
case "$storage_backend" in
    consul)
        consul_path="${CONSUL_PATH:-store/vault/${cluster_name}}"
        consul_token_secret_path="${CONSUL_TOKEN_SECRET_PATH:-vault/${cluster_name}/consul-token}"
        consul_token=$(
            aws secretsmanager get-secret-value \
                --output json \
                --region "$aws_region" \
                --secret-id "$consul_token_secret_path" \
            | jq -r .SecretString
        )
        [[ -n $consul_token ]] || die "Could not read Consul token from $consul_token_secret_path in $aws_region"
        ;;

    dynamodb)
        dynamodb_table="${DYNAMODB_TABLE:-vault-${cluster_name}}"
        ;;

    file)
        storage_dir=/var/lib/vault
        ;;

    *)
        die "Storage backend '$storage_backend' is not supported"
        ;;
esac

# shellcheck disable=SC2154
case "$unseal_method" in
    awskms)
        kms_key="$AUTO_UNSEAL_AWSKMS_KEY"
        [[ -n $kms_key ]] || die "AUTO_UNSEAL_AWSKMS_KEY must be specified for 'awskms' unseal type."
        ;;
    secretsmanager|manual)
        ;;
    *)
        die "Unseal method '$unseal_method' is not supported"
        ;;
esac

# shellcheck disable=SC2154
case "$telemetry" in
    datadog|none)
        ;;
    *)
        die "Telemetry '$telemetry' is not supported"
        ;;
esac

user_conf_dir=/etc/vault-bootstrap/user-conf.d
conf_dir=/etc/vault/conf.d
var_dir=/var/lib/vault-bootstrap

tmp_dir=$( create_tmpdir consul-bootstrap )
chmod 755 "${tmp_dir}"
info "Building configuration files in ${tmp_dir}"

info "Building 00-storage.hcl..."
case "$storage_backend" in
    consul)
        cat > "${tmp_dir}/00-storage.hcl" <<HCL
storage "consul" {
  path         = "$consul_path"
  token        = "$consul_token"
  service_tags = "$cluster_name"
}
HCL
        ;;

    dynamodb)
        cat > "${tmp_dir}/00-storage.hcl" <<HCL
storage "dynamodb" {
  region     = "$aws_region"
  table      = "$dynamodb_table"
  ha_enabled = "true"
}
HCL
        ;;

    file)
        cat > "${tmp_dir}/00-storage.hcl" <<HCL
storage "file" {
  path = "$storage_dir"
}
HCL
        ;;
esac

info "Building 00-cluster-name.hcl..."
cat > "${tmp_dir}/00-cluster-name.hcl" <<HCL
cluster_name = "$cluster_name"
HCL

info "Building 00-listener.hcl..."
# shellcheck disable=SC2154
cat > "${tmp_dir}/00-listener.hcl" <<HCL
listener "tcp" {
  address = "127.0.0.1:${port}"
  tls_disable = "true"
}

listener "tcp" {
  address = "${ip}:${port}"
  cluster_address = "${ip}:${cluster_port}"
  tls_disable = "true"
  x_forwarded_for_authorized_addrs = ["10.0.0.0/8"]
  x_forwarded_for_reject_not_present = false
  x_forwarded_for_reject_not_authorized = false
}

api_addr = "http://${ip}:${port}"
cluster_addr = "http://${ip}:${cluster_port}"
HCL

info "Building 00-logs.hcl..."
cat > "${tmp_dir}/00-logs.hcl" <<HCL
log_format = "json"
HCL

info "Building 00-ui.hcl..."
# shellcheck disable=SC2154
cat > "${tmp_dir}/00-ui.hcl" <<HCL
ui = $ui
HCL

info "Building 00-cache.hcl..."
# shellcheck disable=SC2154
cat > "${tmp_dir}/00-cache.hcl" <<HCL
cache_size = "$cache_size"
HCL

case "$unseal_method" in
    awskms)
        cat > "${tmp_dir}/00-seal.hcl" <<HCL
seal "awskms" {
  region     = "$aws_region"
  kms_key_id = "$kms_key"
}
HCL
        ;;
esac

case "$telemetry" in
    datadog)
        cat > "${tmp_dir}/00-telemetry.hcl" <<HCL
telemetry {
  disable_hostname = true
  dogstatsd_addr   = "localhost:8125"
  dogstatsd_tags   = ["vault-cluster:${cluster_name}"]
  prometheus_retention_time = "30s"
}
HCL
        ;;
esac

# then copy over any files from user-conf
if [[ -n "$( find "${user_conf_dir}" -type f 2>/dev/null )" ]]; then
    info "Copying files from ${user_conf_dir}..."
    cp -pr "${user_conf_dir}"/* "${tmp_dir}"
fi

# backup the old config directory
info "Replacing old configuration..."
conf_backup_dir="${var_dir}/conf-backup/conf-$(date +%s)"
mkdir -p "$( dirname "$conf_backup_dir" )"
if [[ -e $conf_dir ]]; then
    mv "$conf_dir" "$conf_backup_dir" \
        || die "Could not backup old config directory"
fi

mv "$tmp_dir" "$conf_dir" \
    || die "Could not move new configuration into place"

info "Done"
