#!/bin/bash 

# Assumes you have a DIGITALOCEAN_TOKEN env var pre-set 
# Assumes you have terraform and mutagen installed 
# Assumes DO has an SSH key uploaded
DO_REGION="sgp1" # Set to DO region: https://www.digitalocean.com/docs/platform/availability-matrix/
SSH_KEY_FINGERPRINT="your-key-fingerprint" # You can find this in your control panel 

if [ -z $DIGITALOCEAN_TOKEN ]; then
  exit 1 
fi 

cat <<EOF > terraform.tf 
  provider "digitalocean" {}

  resource "digitalocean_droplet" "web" {
    image  = "ubuntu-20-04-x64"
    name   = "dev"
    region = "$DO_REGION"
    size   = "s-1vcpu-1gb"
    ssh_keys = ["$SSH_KEY_FINGERPRINT"]
  }

  output "ip_addr" {
    value = digitalocean_droplet.web.ipv4_address
  }
EOF

terraform init
terraform apply -auto-approve
export REMOTE_IP_ADDR=`terraform output | ruby -e "puts STDIN.read.split.last"`

sleep 5 # give DO enough time to come up 

ssh -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null root@$REMOTE_IP_ADDR <<'ENDSSH'
  apt install --yes make ruby ruby-dev build-essential
  gem install bundler
  bundle config set path 'vendor/bundle'
ENDSSH

mutagen sync create --sync-mode=one-way-safe --name=devproj-code . root@$REMOTE_IP_ADDR:~/
mutagen sync flush devproj-code
ssh -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null root@$REMOTE_IP_ADDR "bundle install"

echo "Dev box ready: ssh root@$REMOTE_IP_ADDR"

# next line only works once the remote service is actually up 
# mutagen forward create --name=devproj tcp:localhost:9292 root@$REMOTE_IP_ADDR:tcp:localhost:9292

# TODO: up/down/console/forward/run commands 
# TODO: Vultr + other cloud provider support 

# Down with: 
# mutagen sync terminate -a && terraform destroy -auto-approve